socket基本连接

服务器端:
public class ServerSocketConnection extends  Thread{
private Socket client;

ServerSocketConnection(Socket client){
this.client=client;
}
public void run(){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println("Server received:"+str);
out.println("服务器收到了....");
out.flush();
if (str.equals("end"))
break;
}

client.close();
} catch (IOException ex) {
} finally {
}
}

public static void main(String[] args) throws IOException{
//这个程序的主要目的在于服务器不断接收客户机所写入的信息只到。客户机发送"End"字符串就退出程序。
//并且服务器也会做出"Receive"为回应。告知客户机已接收到消息。多线程
ServerSocket server=new ServerSocket(9766);
while(true){
ServerSocketConnection ssc=new ServerSocketConnection(server.accept());
ssc.start();
}

}

}

客户端:
public class ClientSocketConnection {

static Socket server;
public static void main(String[] args) {
//客户机代码则是接受客户键盘输入,并把该信息输出,然后输出"End"用来做退出标识。
try {
// server = new Socket("192.168.5.166", 9766);
server = new Socket(InetAddress.getLocalHost(), 9766);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));

PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = br.readLine();
out.println("收到 from server:"+str);
out.flush();
System.out.println(in.readLine());
if (str.equals("end")) {
break;
}
}

server.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

可先启动服务器端ServerSocketConnection ,再启动ClientSocketConnection测试

你可能感兴趣的:(多线程,thread,socket)