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

📄 serverthread.java

📁 JAVA实现的聊天工具,可以容纳最多10个用户 1.本系统需要JDK1.5 或更高版本的支持。 2.serverDatabase为服务器端的数据文件. 若使用现有数据,可用帐号:1, 密码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
//when server accept,this thread is constructed to communicate
import java.io.*;
import java.net.*;
import java.util.*;

public class ServerThread implements Runnable{
	private static boolean signal=true;
	private boolean processing=false;
	private Socket tempSocket ;
	private ObjectInputStream ois; //to receive data
	private ObjectOutputStream oos; //to send data
	private ByteArrayOutputStream baos;
	private ByteArrayInputStream bais;
	private DataInputStream dis;
	private DataOutputStream dos;
	private byte[] byteArray;
	
	private static List<Socket> pool=new LinkedList<Socket>();
	
	public ServerThread(){
	}
	
    public void run() {    	
    	while(signal){
    		synchronized (pool){
    			while(pool.isEmpty()){
    				try{
    					pool.wait();
    				}catch(InterruptedException e){
    					System.out.println(e+" ServerThread "+e.getMessage());
    				}
    			}
    		}
    		
    		tempSocket=pool.remove(0);
    		while(processing); //loops when any other task is functioning
    		processing=true;   //processing begin
    		handleConnection();
    		while(processing);
    		closeSocketStreams();
    	}
    }
    
    static void processRequest(Socket temp){ //called in Server.java
    	synchronized(pool){
    		pool.add(temp); //pool is sychronized,so when adding new socket,no one can access it
    		pool.notifyAll(); //after adding, notify all
    	}
    }
    
    static void exit(){
    	List<Long> tempOnlineClients=(LinkedList<Long>)Server.getServerDatabase().getOnlineClientsList();
    	System.out.println("online clisnts list:"+tempOnlineClients); //**test
    	String tempIP=null;
    	long tempID;
    	Socket tempSocket=null;
    	ByteArrayOutputStream tempBaos;
    	ObjectOutputStream tempOos;
    	DataOutputStream tempDos;
    	ServerClientData tempData;
    	if(tempOnlineClients!=null)
    		//inform all clients that server quit
    		for(int i=0;i<tempOnlineClients.size();i++){
    			tempID=tempOnlineClients.get(i).longValue();
    			tempIP=Server.getServerDatabase().findClient(tempID).getIP();
    			System.out.println("send server-quit info to ID:"+tempID+" IP:"+tempIP); //**test
    			try{
    				tempSocket=new Socket(tempIP,4445);
    				//tempOos=new ObjectOutputStream(/*new BufferedOutputStream(*/
    						//tempSocket.getOutputStream());
    				tempData=new ServerClientData("serverQuit","");
    				tempBaos=new ByteArrayOutputStream(6000);
    				tempOos=new ObjectOutputStream(tempBaos);
    				tempOos.flush();
    				tempOos.writeObject(tempData);
    				tempOos.flush();
    				byte[] tempByte=new byte[6000];
    				tempByte=tempBaos.toByteArray();
    				tempDos=new DataOutputStream(tempSocket.getOutputStream());
    				tempDos.write(tempByte,0,tempByte.length);
    				if(tempData==null){    //**test
    					System.out.println("Warning: to send null data!");
    				}
    				//for(int j=0;j<10000000;j++);    				
    				tempBaos.close();   				
    				tempOos.close();
    				tempDos.close();
    				tempSocket.close();
    			}catch(ConnectException e){	
    			}
    			catch(UnknownHostException e){
    				System.out.println(e+" ServerThread "+e.getMessage());
    			}catch(IOException e){
    				System.out.println(e+" ServerThread "+e.getMessage());
    			} 
    			
    		}
    	signal=false;
    	ServerThreadPoolBuilder.exit(); //shut down thread-pool
    }
    
    private void initiateSocketStreams(){
    	//initiate streams
    	try{
    		//BufferedInputStream bis=new BufferedInputStream(tempSocket.getInputStream());
    		//BufferedOutputStream bos=new BufferedOutputStream(tempSocket.getOutputStream());
    		/*System.out.println("send buffer size:"+tempSocket.getSendBufferSize()); //**test
    		System.out.println("recv buffer size:"+tempSocket.getReceiveBufferSize());
    		System.out.println("linger time:"+tempSocket.getSoLinger());
    		System.out.println("time out:"+tempSocket.getSoTimeout());*/
    		
    		baos=new ByteArrayOutputStream(6000);
    		oos=new ObjectOutputStream(baos);
    		dos=new DataOutputStream(tempSocket.getOutputStream());
    		dis=new DataInputStream(tempSocket.getInputStream());
    	}catch(IOException e){
    		System.out.println(e+" ServerThread "+e.getMessage());
    	}
    }
    
    private void closeSocketStreams(){
    	try{
    		baos.close();
    		oos.close();
    		dos.close();
    		dis.close();
    		tempSocket.close();
    	}catch(IOException e){
       		System.out.println(e+"  ServerThread "+e.getMessage());
       	}
    }
    
    private void handleConnection(){
    	initiateSocketStreams();    	
    	//get communicate object
    	Communicate d=null;
    	try{
    		byteArray=new byte[6000];
    		dis.read(byteArray,0,6000);
    		bais=new ByteArrayInputStream(byteArray);
    		ois=new ObjectInputStream(bais);
    		d=(Communicate)ois.readObject();
    		//for(int j=0;j<1000000;j++); //**test
    	}catch(IOException e){
    		System.out.println(e+" !!ServerThread "+e.getMessage()+"\n");
    		e.printStackTrace();
    	}catch(ClassNotFoundException e){
    		System.out.println(e+" ServerThread "+e.getMessage());
    	}
    	
    	if(d==null){
    		System.out.println("!!Get null data!!");  //**test
    		processing=false;
    		return;
    	}
    	String type=d.getType(); //get info type
    	
    	if(type.equals("register")){  //register request
        	try{
        		dealRegister(d);
        	}catch(IOException e){
           		System.out.println(e+"  ServerThread "+e.getMessage());
           	}
    	}
        else if(type.equals("online")){  //online request
        	try{
        		dealOnline(d);
        	}catch(IOException e){
           		System.out.println(e+"  ServerThread "+e.getMessage());
           	}
        }
        else if(type.equals("clientQuit")){
        	dealQuit(d);
        }
        else if(type.equals("addFriends")){
        	addFriends(d);
        }
        else if(type.equals("delFriends")){
        	try{
        		delFriends(d);
        	}catch(IOException e){
           		System.out.println(e+"  ServerThread "+e.getMessage());
           	}
        }
    }    
           
    private void dealRegister(Communicate d) throws IOException{ //called when a client want to register
    	ServerClientData scd=(ServerClientData)d;
    	String name=scd.getName();
    	String password=scd.getPassword();
    	
    	String mail=scd.getMail();
    	String age=scd.getAge();
    	String sex=scd.getSex();
    	String from=scd.getFrom();
    	InetAddress ip=tempSocket.getInetAddress();
    	//System.out.println("client's ip:"+ip.toString());
    	Server.getServerDatabase().addClient(new ClientData(ip.toString().substring(1),name,password,mail,age,sex,from));
    	
    	long id=Server.getServerDatabase().getNewClientID(); //object to confirm register
    	infoBack(new ServerClientData("registerConfirm","true",id));
    	ServerControlGUI.resetNumber();
    	if(ServerControlGUI.isClientGUIStarted())
    		ClientGUI.resetNumber();
    	processing=false;
    }
    //called when a client want to go online,send to client any friend's ip if online
    private void dealOnline(Communicate d) throws IOException{ 
    	ServerClientData scd=(ServerClientData)d;
    	long id=scd.getID();
    	String pw=scd.getPassword();
    	boolean successful;
    	String info="";
    	
    	ClientData cd=Server.getServerDatabase().findClient(id);
    	if(cd==null ) {//id doesn't find
    		//System.out.println("ID:"+id+" dosen't exit!");
    		info="ID doesn't exit!";
    		successful=false;
    	}
    	else if( !pw.equals(cd.getPassword()) ){ //password doesn't equal
    		info="Password doesn't equal!";
    		successful=false;
    	}
    	else if(cd.isOnline()){  //already online
    		info="ID has already online!";
    		successful=false;
    	}
    	else{
    		InetAddress ip=tempSocket.getInetAddress();
    		successful=Server.getServerDatabase().setOnline(id,ip.toString().substring(1));
    	}
    	
    	String tf;
    	if(successful)
    		tf="true";
    	else 
    	    tf="false";
    	infoBack(new ServerClientData("confirmOnline",tf,info));
    	if(successful){
    		ServerControlGUI.resetNumber();
        	if(ServerControlGUI.isClientGUIStarted())
        		ClientGUI.resetNumber();
    		checkOnlineFriends(id); //start another task
    		//System.out.println("to checkOnlineFriends()"); //**
    	}
    	else
    		processing=false;
    }    
    
    private void dealQuit(Communicate d){
    	ServerClientData scd=(ServerClientData)d;
    	long id=scd.getID();
    	
    	if(!Server.getServerDatabase().contains(id)){//if id doesn't exit--maybe a online client has been deled
    		processing=false;
    		return;
    	}
    	
		//server may fail and data hasn't been save. so some clients may not receive server-quit info.    	
		LinkedList<Long> tempOnlineClients=(LinkedList<Long>)Server.getServerDatabase().getOnlineClientsList();
		if(tempOnlineClients.contains(new Long(id))){			
	    	Server.getServerDatabase().setOffline(id);
	    	System.out.println(id+" quit");  //**test
	    	
	    	ServerControlGUI.resetNumber();
	    	if(ServerControlGUI.isClientGUIStarted())
	    		ClientGUI.resetNumber();
			checkOfflineFriends(id); //inform friends this client's quit
		}
		else
			processing=false;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -