📄 serverthread.java
字号:
/**
* 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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -