?? chatserver.java
字號:
import java.net.*;
import java.io.*;
import java.util.*;
public class chatserver
{
public static void main(String[] args) throws IOException
{
ServerSocket socket=null;
Vector m_threads=new Vector();
System.out.println("Listen...");
try
{
socket=new ServerSocket(5555);
}
catch(Exception e)
{
System.out.println("new ServerSocket() failed!");
return;
}
try
{
int nid=0;
while(true)
{
//監聽是否有新chat Applet連接到Server,
//程序會陷入到該語句,直到有新的連接產生。
Socket s=socket.accept();
System.out.println("accepted");
//創建一個新的ServerThread
ServerThread st=new ServerThread(s,m_threads);
//為該線程設置一個ID號。
st.setID(nid++);
//將該線程加入到m_threads Vector中。
m_threads.addElement(st);
new Thread(st).start();
//通知所有Chat Applet有一個新的網友加入
for(int i=0;i<m_threads.size();i++)
{
ServerThread st1=(ServerThread)m_threads.elementAt(i);
st1.write("<#>welcome"+st.getID()+"to enter chatroom!");
}
System.out.println("Listen again...");
}
}
catch(Exception e)
{
System.out.println("Server is down...");
}
}
}
/*
*ServerThread是監聽線程,用于監聽對應的Chat Applet是否有信息傳來。
*/
class ServerThread implements Runnable
{
Vector m_threads;
Socket m_socket=null;
DataInputStream m_in=null;
DataOutputStream m_out=null;
int m_nid;
//初始化該線程
public ServerThread(Socket s,Vector threads)
{
m_socket=s;
m_threads=threads;
try
{
// System.out.println(inetaddr);
m_in=new DataInputStream(m_socket.getInputStream());
m_out=new DataOutputStream(m_socket.getOutputStream());
}
catch(Exception e)
{
}
}
//線程的執行體
public void run()
{
System.out.println("Thread is runing");
try
{
while(true)
{
//監聽對應的Applet是否傳來消息
//程序陷入到m_in.readUTF()中,直到有信息傳來才返回。
String s=m_in.readUTF();
if(s==null)
break;
if(s.equals("leave"))
for(int i=0;i<m_threads.size();i++)
{
ServerThread st=(ServerThread) m_threads.elementAt(i);
st.write("***"+getID()+"leave..."+"***");
m_threads.removeElement(this);
}
else
{
for(int i=0;i<m_threads.size();i++)
{
ServerThread st=(ServerThread) m_threads.elementAt(i);
st.write("<"+getID()+">"+s);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
//從m_threads Vector中刪除該線程,表示該線程已經離開chat room
//m_threads.removeElement(this);
try
{
m_socket.close();
}
catch(Exception e)
{
}
}
//write()將msg送回對應的Applet
public void write(String msg)
{
synchronized(m_out)
{
try
{
m_out.writeUTF(msg);
}
catch(Exception e)
{
}
}
}
//獲得該線程的ID
public int getID()
{
return m_nid;
}
//設置線程的ID
public void setID(int nid)
{
m_nid=nid;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -