?? server.java
字號:
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;
public class Server
{
private ServerSocket ss;
private Hashtable<Socket, DataOutputStream> customerList = new Hashtable<Socket, DataOutputStream>();
public Server(int port) throws IOException
{
listen(port);
}
private void listen(int port) throws IOException
// 1.監聽本地端口
{
ss = new ServerSocket(port);
System.out.println("Listening on " + ss);
while (true)// while - Accept循環
{
Socket s = ss.accept();
System.out.println("Connection from " + s);
// 獲得這個連接的輸出流
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
// 2.把當前的客戶端連接和輸出流 保存到客戶端列表中
customerList.put(s, dout);
// 3.創建 線程 和 客戶端通信
new ServerThread(this, s);
}
}
// 獲得客戶端列表的地址空間
Enumeration getcustomerList()
{
return customerList.elements();
}
// 發送信息給所有客戶端
void sendToAll(String message)
{
// 避免 有人退出
synchronized (customerList)
{
// 獲得每一個 客戶端 的 輸出流
for (Enumeration e = getcustomerList(); e.hasMoreElements();)
{
DataOutputStream dout = (DataOutputStream) e.nextElement();
// 把 信息 發送給每一個客戶端
try
{
dout.writeUTF(message);
} catch (IOException ie)
{
System.out.println(ie);
}
}
}
}
//在客戶端列表中 刪除退出聊天的用戶
void removeConnention(Socket s)
{
//同步
synchronized(customerList)
{
//智能提示xxx退出聊天室
System.out.println("Removing connection to ");
//在列表中刪除
customerList.remove(s);
//關閉斷開 連接
try
{
s.close();
}
catch(IOException ie)
{
System.out.println(ie);
ie.printStackTrace();
}
}
}
public static void main(String args[]) throws Exception
{
if (args.length==1)
{
int port =Integer.parseInt(args[0]);
new Server(port);
}
else
{
System.out.println("Usage: java Server Port");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -