package com.demo;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;
public class ServiceSoketServerListenerThread extends Thread{
//监听端口
private int port;
//是否开启
private ServerSocket serverSocket=null;
//多线程下操作list
public static List<User> socketList=new ArrayList<User>();
private JTextArea textField;
public ServiceSoketServerListenerThread(int port,JTextArea textField) {
this.port = port;
this.textField=textField;
}
@Override
public void run() {
try {
serverSocket = new ServerSocket(port);
System.out.println("服务器开启");
while (true) {
Socket socket = serverSocket.accept();
User user = new User();
user.setSocket(socket);
//synchronized 同步 也可不加
synchronized (socketList) {
socketList.add(user);
}
System.out.println("有客户连接");
new SocketData2(socket, textField).start();
}
} catch (IOException e) {
System.out.println("服务器关闭");
// e.printStackTrace();
}
}
// 转发消息
public static void send(String msg) {
synchronized (socketList) {
for (User user : socketList) {
try {
user.getSocket().getOutputStream().write((msg).getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
/* for (Socket socket : socketList) {
try {
socket.getOutputStream().write((msg).getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
try {
DataOutputStream dis=new DataOutputStream(socket.getOutputStream());
dis.writeUTF("服务器:"+textField_2.getText());
} catch (IOException e1) {
socketList.remove(socket);
System.out.println("对方退出了!我从List里面去掉了!");
e1.printStackTrace();
}
}*/
}
public void stopService() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<User> getSocketlist() {
return socketList;
}
}
最近下载更多
qwertasdfgkwuejwjwjw LV1
2024年6月27日
jxd2007kl LV2
2023年11月29日
谢小饭_ LV8
2022年1月21日
9843637 LV9
2021年12月15日
tangjj7260 LV18
2021年12月10日
dfz12345 LV4
2021年12月8日
橙 LV2
2021年6月16日
miner22 LV9
2021年5月27日
chat511 LV3
2021年5月12日
15508061020 LV1
2020年9月3日
最近浏览更多
13133117021 LV5
2024年12月23日
124324343 LV1
2024年6月29日
qwertasdfgkwuejwjwjw LV1
2024年6月27日
taoshen95 LV16
2024年6月18日
周鸣郝 LV2
2024年5月26日
微信网友_7004855557083136 LV1
2024年5月22日
zeng1206 LV7
2023年12月28日
jxd2007kl LV2
2023年11月29日
jidea LV2
2023年11月29日
阿布屋脊 LV7
2023年8月15日

