📄 server_socket.java
字号:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
public class Server_Socket implements Runnable{
private Frame f;
public static TextArea ta1;
private Label l1;
static final int PORT=8888;
ServerSocket serverSocket;
private static BufferedReader in;
private static PrintWriter out;
Thread chatAcceptThread; //客户端请求接受线程
BroadcastThread broadcastThread;
java.util.Vector clients; //CommunicateThread向量
java.util.Vector clientsInfor; //简单客户信息向量
public static int index=0;
public void display()throws IOException{ //服务器端简单界面处理
f=new Frame("聊天室");
f.setSize(470,250);
f.setLocation(20,20);
f.setBackground(Color.pink);
f.setLayout(new FlowLayout(FlowLayout.CENTER));
l1=new Label("欢迎您进入【爱★我★该★爱】聊天室",Label.CENTER);
ta1=new TextArea();
ta1.setEditable(false);
f.add(l1);
f.add(ta1);
f.addWindowListener(new WinClose());
f.setVisible(true);
}
private void serverListen(){ //客户端请求监听程序
try{
serverSocket=new ServerSocket(PORT);
}catch(IOException e){
ta1.append("server failed!\n");
}
clients=new java.util.Vector();
clientsInfor=new java.util.Vector();
chatAcceptThread=new Thread(this); //创建新监听线程
chatAcceptThread.start();
broadcastThread=new BroadcastThread(this); //创建新的广播线程
broadcastThread.start();
}
public void run(){
int i=0;
try{
while(true){
Socket socket=serverSocket.accept();
CommunicateThread ct=new CommunicateThread(socket,this,index); //创建新的通讯线程
clients.add(ct); //添加新的通讯线程
i++;
index++;
clientsInfor.add("Client"+i); //添加新的客户端的信息
ta1.append("Client"+i+" join in\n");
}
}catch(IOException e){
}
}
public static void main(String[] args)throws IOException{ //程序入口
Server_Socket server=new Server_Socket();
server.display();
server.serverListen();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -