Server
- 自己创建相应的端口
ServerSocket ss = new ServerSocket(30000);
- 循环运行端口接受函数
while(true) {
Socket s = ss.accept();
socketList.add(s);
new Thread(new ServerThread(s)).start();
}
ServerThread
public ServerThread(Socket s)
throws IOException {
this.s = s;
br = new BufferReader(new InputStreamReader(s.getInputStream()));
}
public void run {
try {
String content = null;
while((content = readFromClinet()) != null) {
for (Socket s : MyServer.socketList) {
PrintStream ps = new PrintStream(s.getInputStream());
ps.println(content);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
Private String readFromClient() {
try {
return br.readLine();
}
catch (IOException e) {
MyServer.socketList.remove(s);
}
return null;
}
MyClient
1.创建一个属于自己的接口连接到服务器
Socket s = new Socket("127.0.0.1" , 30000);
new Thread(new ClientThread(s)).start();
2.当从系统检测到有输入就输出
PrintStream ps = new PrintStream(s.getOutputStream());
String line = null;
BufferReader br = new BufferReader(new InputStreamReader(system.in));
while ((line = br.readLine()) != null) {
ps.println(line);
}
ClinetThread
public ClientThread(Socket s)
throws IOException {
this.s = s;
br = new BufferReader(new InputStreamReader(s.getInputStream()));
}
public void run() {
try {
String content = null;
while ((content = br.readLine()) != null) {
System.out.println(content);
}
}
catch (Exception e) {
e.printStackTrace();
}
}