- Socket聊天服務(wù)器任務(wù):ChatServer類負(fù)責(zé)開啟Server端服務(wù);ReceiveMsg負(fù)責(zé)接收消息炊甲;SendMsg負(fù)責(zé)發(fā)送消息模狭;Server端響應(yīng)請(qǐng)求,向Client端返回?cái)?shù)據(jù)兵钮。
public class ChatServer extends Thread {
private ChatServer() throws IOException {
//創(chuàng)建Socket服務(wù)
CreateSocket();
}
public void run() {
Socket client;
//定義接收的文本
String txt;
try {
//始終在監(jiān)聽
while (true) {
//開啟線程實(shí)時(shí)監(jiān)聽socket端口
//獲取應(yīng)答消息
client = ResponseSocket();
//響應(yīng)客戶端連接請(qǐng)求
while (true) {
//接受客戶端消息
txt = ReceiveMsg(client);
//連接獲得客戶端發(fā)來(lái)消息
//并將其顯示在Server端屏幕上
SendMsg(client, txt);
//向客戶端返回消息
if (true) {
break;
}
//中斷,繼續(xù)等待連接請(qǐng)求
}
//關(guān)閉此次連接
CloseSocket(client);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//定義一個(gè)ServerSocket對(duì)象
private ServerSocket server = null;
//定義端口
private static final int PORT = 5000;
//定義寫buffer
private BufferedWriter writer;
//定義讀buffer
private BufferedReader reader;
//實(shí)例化ServerSocket
private void CreateSocket() throws IOException {
server = new ServerSocket(PORT, 100);
}
//接收消息
private Socket ResponseSocket() throws IOException {
Socket client = server.accept();
return client;
}
//關(guān)閉打開的連接和緩存
private void CloseSocket(Socket socket) throws IOException {
reader.close();
writer.close();
socket.close();
}
//封裝發(fā)送消息的方法
private void SendMsg(Socket socket, String Msg) throws IOException {
//要發(fā)送的消息寫入BufferedWriter中
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//添加空行分隔符
writer.write(Msg + "\n");
//刷新舌界,發(fā)送
writer.flush();
}
//接收消息的方法
private String ReceiveMsg(Socket socket) throws IOException {
//保存到讀buffer
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//將接收到的信息保存到字符串中
String txt = "Server send:" + reader.readLine();
return txt;
}
}
啟動(dòng)服務(wù)器的代碼如下
ChatServer chatServer = null;
try {
chatServer = new ChatServer();
} catch (IOException e) {
e.printStackTrace();
}
//檢測(cè)服務(wù)器是否已經(jīng)起動(dòng)掘譬,如果沒(méi)有則啟動(dòng)服務(wù)器
if(chatServer != null){
chatServer.start();
}
客戶端的任務(wù):客戶端發(fā)起連接請(qǐng)求,并向服務(wù)器發(fā)送數(shù)據(jù)呻拌;客戶端接收服務(wù)器的數(shù)據(jù)葱轩。
//客戶端獲取消息類
private Socket RequestSocket(String host, int port) throws UnknownHostException, IOException {
Socket socket = new Socket(host, port);
return socket;
}
//客戶端發(fā)送消息類
private void SendMsg(Socket socket, String msg) throws IOException {
//要發(fā)送的消息寫入BufferedWriter中
BufferedWriter wirter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//格式轉(zhuǎn)換
wirter.write(msg.replace("\n", " ") + "\n");
//刷新,發(fā)送
wirter.flush();
}
//客戶端接收消息類
private String ReceiveMsg(Socket socket) throws IOException {
//寫入讀buffer
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//將信息保存到字符串中
String txt = reader.readLine();
return txt;
}