服务器端:
public class Server {
public static void main(String[] args) {
//List<Socket> lists = new ArrayList<>();
try {
//System.out.println(InetAddress.getLocalHost().getHostAddress());
//192.168.13.37
ServerSocket server = new ServerSocket(909);
Socket c = server.accept();
System.out.println("有人上线");
PrintWriter out = new PrintWriter(c.getOutputStream()); //发信息
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); //接信息
while(true) {
//先收信息
String msg = br.readLine();
System.out.println(msg);
//发信息
System.out.println("发信息:");
String info = new Scanner(System.in).nextLine() + "\r\n";
out.write(info);
out.flush();
}
//while(true) {
// Socket c = server.accept();//中断
// lists.add(c);
// System.out.println("有人连线");
//}
} catch (Exception e) {
e.printStackTrace();
}
}
客户端:
public class client {
public static void main(String[] args) {
try {
//服务器端的IP地址
Socket c= new Socket("192.168.13.37",909);
PrintWriter out= new PrintWriter(c.getOutputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(c.getInputStream()));
while (true) {
System.out.println("发信息:");
String masg =new Scanner(System.in).nextLine()+"\r\n";
out.write(masg);
//刷新
out.flush();
//TimeUnit.SECONDS.sleep(5);
String info=br.readLine();
System.out.println(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}