在上一个博客代码中进行修改:
1.MyServerSocket类
package com.jikexueyuan.testmyserversocket.main;
public class MyServerSocket {
public static void main(String[] args) {
new ServerListner().start();
}
}
2.ServerListner类
package com.jikexueyuan.testmyserversocket.main;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class ServerListner extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
Socket socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "有客户端链接到了本机的12345端口");
ChatSocket cs = new ChatSocket(socket);
cs.start();
ChatManager.getChatManager().add(cs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.ChatSocket类
package com.jikexueyuan.testmyserversocket.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
public class ChatSocket extends Thread {
Socket socket;
public ChatSocket(Socket s) {
this.socket = s;
}
public void out(String out) {
try {
socket.getOutputStream().write(out.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
ChatManager.getChatManager().publish(this, line);
}
br.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.ChatManager类
package com.jikexueyuan.testmyserversocket.main;
import java.util.Vector;
public class ChatManager {
private ChatManager() {
}
private static final ChatManager cm = new ChatManager();
public static ChatManager getChatManager() {
return cm;
}
Vector<ChatSocket> vector = new Vector<ChatSocket>();
public void add(ChatSocket cs) {
vector.add(cs);
}
public void publish(ChatSocket cs, String out) {
for (int i = 0; i < vector.size(); i++) {
ChatSocket csChatSocket = vector.get(i);
if (!cs.equals(csChatSocket)) {
csChatSocket.out(out);
}
}
}
}
5.运行结果:
1.打开两个cmd,分别输入如图指令
2.两个cmd客户端连接成功
3.只要在一个窗口输入数据,另外一个窗口就会接收到