⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 server.java

📁 最基础的网络聊天器TCP 有兴趣的朋友可以下载来
💻 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 + -