📄 server4.java
字号:
import java.io.*;
import java.net.*;
public class Server4{
static int port=2121;
static String ClientName="No client";
public static String getClientName(){
return ClientName;
}
synchronized public static void setClientName(String name){
ClientName=name;
try{
Thread.sleep(5000);
}catch(InterruptedException e){
System.out.print(e.toString());
}
ClientName="No client";
}
public static void main(String[] args)throws IOException{
int count=0;
ServerSocket server=new ServerSocket(port);
System.out.println("Server listening on Port "+port+".");
printer p=new printer();
p.start();
while(true){
count++;
ServerThread thrd=new ServerThread(server.accept(),"CLIENT "+count);
thrd.start();
}
}
}
class printer extends Thread{
public void run(){
while(true){
System.out.println(Server4.getClientName());
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.print(e.toString());
}
}
}
}
class ServerThread extends Thread{
private Socket client;
private String id;
public ServerThread(Socket c,String i){
this.client=c;
this.id=i;
}
public void run(){
try{
System.out.println("---Connected to client "+id+".---");
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out=new PrintWriter(client.getOutputStream());
out.println(id);
out.flush();
while(true){
String str=in.readLine();
if(str.equals("end")){
System.out.println("---Disconnected to client "+id+".---");
break;
}
Server4.setClientName(str);
out.println("Request accepted");
out.flush();
}
client.close();
}catch(IOException ex){
}
finally{
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -