📄 server.java
字号:
//server
import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String[] args) throws Exception {
try{
ServerSocket listensocket=new ServerSocket(7200);
List list=new ArrayList(); //build a list for all connections to this server;
while(true){
Socket clientsocket=listensocket.accept();
list.add(clientsocket);
Thread t=new Connection(clientsocket,list);
t.start();
}
}
catch (IOException e) {
System.out.println("Listen:"+e.getMessage());
}
}
}
class Connection extends Thread{
Socket s;
DataInputStream in;
DataOutputStream out;
List list;
public Connection(Socket clientsocket, List list) {
this.s = clientsocket;
this.list = list;
try {
in=new DataInputStream(s.getInputStream());
out=new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
System.out.println("Connection:"+e.getMessage());
}
}
public void run(){
while(true){
try {
String name=in.readUTF();
String str=in.readUTF();
if (str==null) return;
Iterator it=list.iterator();
while(it.hasNext())
// check whether there are elements in the list,and send messages to all clients
{
Socket socket=(Socket)(it.next());
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
out.writeUTF(name+""+"says"+":"+"("+new Date()+")");
out.writeUTF(str);
out.flush();
}
}
catch (EOFException e) {
System.out.println("EOF:"+e.getMessage());
}
catch (IOException e) {
System.out.println("IO:"+e.getMessage());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -