⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server4.java

📁 Server-Client 通信模拟,支持多线程.当有多个用户链接时,服务器只与其中一个链接,其他的排队等待.每隔5秒,服务器会选择队列的下一个进行通信.
💻 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 + -