📄 server.java
字号:
package cn.com.sihitech.cc.chat;
import java.io.*;
import java.net.*;
import java.util.Vector;
public class Server {
private ServerSocket serverSocket = null;
public static int port = 5555;
private boolean listening = true;
Vector clientSockets = new Vector(10);
public Server() throws IOException {
/*
try {
serverSocket = new ServerSocket(port); //监听端口
}
catch (IOException ex) {
System.err.println("listen fail:" + port + ":" + ex);
throw ex;
}
System.out.println("listen:" + port);
while (listening) {
addClient(serverSocket.accept()); //建立连接
}
serverSocket.close();
*/
System.out.println("***new Server***");
new listenThread(this).start();
}
/**
* 启动服务器线程并把客户端与服务器建立的socket添加到clientSockets中
* @param socket Socket
* @throws IOException
*/
public void addClient(Socket socket) throws IOException {
new ServerThread(socket, this).start(); //启动服务器线程
clientSockets.add(socket); //把客户端socket加入到vector对象中
}
/**
* 把客户端与服务端建立的socket从clientSockets移走
* @param socket Socket
* @throws Exception
*/
public void removeClient(Socket socket) throws Exception {
System.out.println("socket断开:" + socket);
clientSockets.remove(socket); //把客户端的socket从vector对象中移走
}
/**
* 发送信息到socket客户端
* @param msg String
*/
public void send(String msg) {
Socket socket = null;
Vector tempVec = clientSockets; //clientSockets存放所有客户端socket对象信息
int sendCount = tempVec.size(); //客户端数目
System.out.println("sendCount...." + sendCount);
for (int I = 0; I < sendCount; I++) {
try {
socket = (Socket) (tempVec.get(I));
System.out.println("send......" + I + ":" + socket);
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg); //把信息写入到各个客户端
}
catch (IOException ex) {
System.out.println("send..IOException.." + socket + "::::" + ex);
}
catch (Exception ex2) {
System.out.println("send..Exception..");
}
}
}
public static void main(String[] args) throws IOException {
new Server();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -