字體:小 中 大 | |
|
|
2013/05/10 01:51:52瀏覽341|回應0|推薦2 | |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chatserver;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;
public class ChatHandler extends Thread {
static Vector handlers = new Vector( 10 );
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ChatHandler(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"BIG5"));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"BIG5"));
}
public void run() {
String line;
synchronized(handlers) {
handlers.addElement(this);}
// add() not found in Vector class
try
{
while(!(line = in.readLine()).equalsIgnoreCase("/quit"))
{
if(line.equalsIgnoreCase("/ch1"))//聊天室一
{
synchronized(handlers)
{
handlers.removeElement(this);
}
ch1 channl1=new ch1(socket);
channl1.run();
synchronized(handlers)
{
handlers.addElement(this);//增加 沒做會產生死結(Deadlock)斷線
}
}
if(line.equalsIgnoreCase("/ch2"))//聊天室二
{
synchronized(handlers)
{
handlers.removeElement(this);
}
ch2 channl2=new ch2(socket);
channl2.run();
synchronized(handlers)
{
handlers.addElement(this);//增加 沒做會產生死結(Deadlock)斷線
}
}
for(int i = 0; i < handlers.size(); i++)
{
synchronized(handlers)
{
ChatHandler handler =(ChatHandler)handlers.elementAt(i);
if(handler!=this)
{
handler.out.println(line + "");
handler.out.flush();
}
}
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
in.close();
out.close();
socket.close();
}
catch(IOException ioe)
{
}
finally
{
synchronized(handlers)
{
handlers.removeElement(this);
}
}
}
}
}
|
|
( 心情隨筆|心情日記 ) |