怎么用java编写简单客户端程序
发布网友
发布时间:2022-04-26 10:19
我来回答
共1个回答
热心网友
时间:2022-06-27 07:09
我这里有一个例子希望能够帮助你
public class Client{
private Socket socket;
try{
Socket socket=new Socket ("localhoast',8088);
ip=InetAddress.getLocalHost();
String localip=ip.getHostAddress();
System.out.println(localip);
String name=ip.getHostName();
System.out.println(name);
}
catch(Exception e){
}
public void start(){
try{
Run r2=new Run();
Thread t1=new Thread(r2);
t1.setDaemon(true);
t1.start();
Scanner sc=new Scanner(System.in);
OutputStream os=socket.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
PrintWriter writer=new PrintWriter(osw,true);
while(true){
writer.println(sc.nextLine());
}
}catch(Exception e){
}
}
public static void main(String args[]){
Client client=new Client();
client.start();
}
class Run implements Runnable{
public void run() {
while(true){
try {
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
while(true){
String str=br.readLine();
System.out.println("服务器说:"+str);
if("bye".equals(str)){
System.out.println("再见客户端");
System.out.println("聊天结束");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}