聊天室服务端:
/**
* 在线聊天室:服务端
* 使用多线程实现多个客户可以正常收发多条信息
* @author fujun
*
*/
public class Chat{
public static void main(String[] args) throws Exception {
System.out.println("---Server----");
// 1、指定端口使用ServerSocket
ServerSocket socket = new ServerSocket(8888);
while(true)
// 2、阻塞式等待连接accept
Socket server = socket.accept();
System.out.println("一个客户端建立连接");
new Thread(()->{
// 3、接收消息
DataInputStream dis = null;
DataOutputStream dos = null;
try{
dis = new DataInputStream(server.getInputStream());
dos = new DataOutputStream(server.getOutputStream());
}catch (IOException e1) {
e1.printStackTrace();
}
boolean isRunning = true;
while(isRunning ){
String msg;
try{
mag = = dis.readUTF();
// 4、返回消息
dos.writeUTF(msg);
// 释放资源
dos.flush();
}catch(IOException e){
// 停止线程
isRunning = false;
}
}
try{
dos.close();
dis.close();
server.close();
}catch(IOException e){
e.printStackTrace();
}
}).start();
}
}
}
聊天室客户端保持不变!!
/**
* 在线聊天室:客户端
* 使用多线程实现多个客户可以正常收发多条信息
* @author fujun
*
*/
public class TMultiClient {
public static void main(String[] args) throws Exception {
System.out.println("-----Clinet-----");
// 1、建立连接:使用Socket创建客户端 + 服务端的地址和端口
Socket client = new Socket("localhost",8888);
// 2、客户端发送消息
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
DataInputStream dis = new DataInputStream(client.getInputStream());
boolean isRunning = true;
while(isRunning){
String msg = console.readLine();
dos.writeUTF(msg);
dos.flush();
// 3、获取消息
msg = dis.readUTF();
System.out.println(msg);
}
// 释放资源
dos.close();
dis.close();
client.close();
}
}