服务器设计
1.服务器的连接设计
2.服务器的线程设计
创建一对多聊天服务应用
java
/**
* 接收客户端消息的线程类
*/
class ChatReceive extends Thread {
private Socket socket;
public ChatReceive(Socket socket){
this.socket = socket;
}
@Override
public void run(){
this.receiveMsg();
}
/**
* 实现接收客户端发送的消息
*/
private void reveiveMsg(){
try(BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()))
){
while(true){
String msg = br.readLine();
synchronized("abc"){
//把读取到的数据写入公共数据区
ChatRoomServer.buf="["+this.socket.getInetAddress()+"] "+msg;
//唤醒发送消息的线程对象
"abc".notifyAll();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 向客户端发送消息的线程类
*/
class ChatSend extends Thread {
private Socket socket;
public ChatSend(Socket socket){
this.socket = socket;
}
@Override
public void run(){
this.sendMsg();
}
/**
* 将公共数据区的消息发送给客户端
*/
private void sendMsg(){
try(PrintWriter pw = new PrintWriter(this.socket.getOutputStream())
){
while(true){
synchronized("abc"){
//让发送消息的线程处于等待状态
"abc".wait();
//将公共数据区中的消息发送给客户端
pw.println(ChatRoomServer.buf);
pw.flush();
}
}
}catch(Exeception e){
e.printStackTrace();
}
}
}
public class ChatRoomServer {
//定义公共数据区
public static String buf;
public static void main(String[] args){
System.out.println("Chat Server Version 1.0");
System.out.println("Listen at 8888");
try(ServerSocket serverSocket = new ServerSocket(8888)
){
while(true){
Socket socket = ServerSocket.accept();
System.out.println("连接到:"+socket.getInetAddress());
new ChatReceive(socket).start();
new ChatSend(socket).start();
}
}catch(Exception e){
e.printStackTrace();
}
}
}