📄 serverreceivethread.java
字号:
//ServerReceiveThread 类
import javax.swing.*;
import java.io.*;
import java.net.*;
public class ServerReceiveThread extends Thread
{
JTextArea textarea;
JTextField textfield;
JComboBox combobox;
Node client;
UserInfoList userInfoList;
public boolean isStop;
public ServerReceiveThread(JTextArea textarea,JTextField textfield,JComboBox combobox,Node client,UserInfoList userInfoList)
{
this.textarea = textarea;
this.textfield = textfield;
this.client = client;
this.userInfoList = userInfoList;
this.combobox = combobox;
isStop = false;
}
public void run()
{
sendUserList();
while(!isStop && !client.socket.isClosed())
{
try
{
String type = (String)client.input.readObject();
if(type.equalsIgnoreCase("聊天信息"))
{
String toSomebody = (String)client.input.readObject();
String status = (String)client.input.readObject();
String message = (String)client.input.readObject();
String msg = client.username + "对" + toSomebody + "说:" + message + "\n";
textarea.append(msg);
if(toSomebody.equalsIgnoreCase("所有人"))
{
sendToAll(msg);
}
else
{
try
{
client.output.writeObject("聊天信息");
client.output.flush();
client.output.writeObject(msg);
client.output.flush();
}
catch(Exception e){}
Node node = userInfoList.find(toSomebody);
if(node != null)
{
node.output.writeObject("聊天信息");
node.output.flush();
node.output.writeObject(msg);
node.output.flush();
}
}
}
else if(type.equalsIgnoreCase("用户下线"))
{
Node node = userInfoList.find(client.username);
userInfoList.del(node);
String msg = "用户" + client.username + "下线\n";
int count = userInfoList.getCount();
combobox.removeAllItems();
combobox.addItem("所有人");
int i = 0;
while(i < count)
{
node = userInfoList.find(i);
if(node == null)
{
i++;
continue;
}
combobox.addItem(node.username);
i++;
}
combobox.setSelectedIndex(0);
textarea.append(msg);
textfield.setText("在线用户" + userInfoList.getCount() + "人\n");
sendToAll(msg);
sendUserList();
break;
}
}
catch(Exception e){}
}
}
public void sendToAll(String msg)
{
int count = userInfoList.getCount();
int i = 0;
while(i < count)
{
Node node = userInfoList.find(i);
if(node == null)
{
i++;
continue;
}
try
{
node.output.writeObject("聊天信息");
node.output.flush();
node.output.writeObject(msg);
node.output.flush();
}
catch(Exception e){}
i++;
}
}
public void sendUserList()
{
String userlist = "";
int count = userInfoList.getCount();
int i = 0;
while(i < count)
{
Node node = userInfoList.find(i);
if(node == null)
{
i++;
continue;
}
userlist += node.username;
userlist += '\n';
i++;
}
i = 0;
while(i < count)
{
Node node = userInfoList.find(i);
if(node == null)
{
i++;
continue;
}
try
{
node.output.writeObject("用户列表");
node.output.flush();
node.output.writeObject(userlist);
node.output.flush();
}
catch(Exception e){}
i++;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -