serverthread.java

来自「用java写的浏览器的服务器和客户端程序」· Java 代码 · 共 116 行

JAVA
116
字号
/**
 * Email: taorundong@126.com
 *
 * @author taorundong
 * @version 1.00 07/02/04
 */
 
 import java.util.*;
 import java.net.*;
 import java.io.*;
 
 public class ServerThread extends Thread{
 	
 	private
 	People you = null;
 	DataInputStream input = null;
 	DataOutputStream output = null;
 	Hashtable temp = null;
 	Socket clientSocket = null;
 	String name = null;
 	
 	
 	ServerThread (Socket client,Hashtable peopleList){
 		
 		try{
 			input = new DataInputStream(client.getInputStream());
 			output = new DataOutputStream(client.getOutputStream());
 		}
 		catch(Exception e){
 			e.printStackTrace();
 		}
 		
 		temp = peopleList;
 		clientSocket = client;
 		
 		
 	}
 	
 	public void run(){
 		initChating();
		chating();
 	}
 	
 	public void initChating(){
 		
 		try{

 			name = input.readUTF();//the beginning
 			you = new People(name);
 			you.setOutputStream(output);
 			you.setInputStream(input);
 			temp.put(name,you);
 			
 			output.writeUTF("Welcome to the chating room"+"    "+name);
 		}
 		catch(Exception e){
 			System.out.println("init error!");
 			e.printStackTrace();
 		}
 	}
 	
 	public void chating(){
 		
 		String message = null;
 		try{
 			while(!clientSocket.isClosed()){
 				try{
 					message = input.readUTF();
 					outPutToEveryClient(message);
 				}
 				catch(Exception e){
 					System.out.print(you.getName()+"is   out");
 			//Though the JVM will close the socket for you,you should close it yourself
 					clientSocket.close();
 					e.printStackTrace();
 					temp.remove(name);
 			 		System.out.println(temp.elements().hasMoreElements());
 		 			this.destroy();
 				}
 			}
 		}
 		catch(Exception e){
 			e.printStackTrace();
 			System.out.print(you.getName()+"is   out");
 			temp.remove(you);
 		}
 		
 		//close the socket when client get out
 		try{
 			clientSocket.close();
 		}
 		catch(Exception e){
 			e.printStackTrace();
 		}
 	}
 	
 	public void outPutToEveryClient(String message){
 		
 		Enumeration Enum = temp.elements();
 		
 		while(Enum.hasMoreElements()){
 			People client = (People)Enum.nextElement();
 			try{
 				client.getOutputStream().writeUTF(messageIntegrate(message,client.getName()));
 			}
 			catch(Exception e){
 				e.printStackTrace();
 			}
 		}
 	}
 	
 	public String messageIntegrate(String message,String clientName){
 		return message+"   from   "+clientName+"    "+
 		clientSocket.getInetAddress().getHostAddress();
 	}
 }

⌨️ 快捷键说明

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