📄 serverrecsen.java
字号:
import javax.swing.*;
public class ServerRecSen extends Thread{//服务器端信息收发
JTextArea usershow;//用户列表窗口
JTextArea messageshow;//消息窗口
UserLinkList userlinklist;//用户链表
Node client;//用户结点
public ServerRecSen(JTextArea usershow,JTextArea messageshow,
UserLinkList userlinklist,Node client){
this.usershow = usershow;
this.messageshow = messageshow;
this.userlinklist = userlinklist;
this.client = client;
}
public void run(){//启动线程
sendUserList();//发送用户列表给所有用户
while(!client.socket.isClosed()){//接收消息
try{
String type = (String)client.input.readObject();
if(type.equals("聊天消息")){//类型为聊天消息
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";
if(status.equals("悄悄话")){
msg = "[悄悄话]" + msg;
}
messageshow.append(msg);
if(tosomebody.equals("所有人")){//发送消息给所有人
sendToAll(msg);
}
else{
try{//发送消息给发送方
client.output.writeObject("聊天消息");
client.output.flush();
client.output.writeObject(msg);
client.output.flush();
}
catch(Exception e){
//System.out.println(e);
}
Node node = userlinklist.findUser(tosomebody);
if(node != null){//发送消息给接收方
node.output.writeObject("聊天消息");
node.output.flush();
node.output.writeObject(msg);
node.output.flush();
}
}
}
else if(type.equals("用户下线")){//类型为用户下线
Node node = userlinklist.findUser(client.username);
userlinklist.delUser(node);
String msg = "用户<" + client.username + ">下线\n";
int count = userlinklist.getCount();
usershow.setText("");
int i = 0;
while(i < count){
node = userlinklist.findUser(i);
if(node == null){
i++;
continue;
}
usershow.append(node.username);
i++;
}
messageshow.append(msg);
sendToAll(msg);
sendUserList();
break;
}
}
catch(Exception e){
//System.out.println(e);
}
}
}
public void sendUserList(){//发送用户列表给所有用户
String userlist = "";
int count = userlinklist.getCount();
int i = 0;
while(i < count){
Node node = userlinklist.findUser(i);
if(node == null){
i++;
continue;
}
userlist += node.username;
userlist += '\n';
i++;
}
i = 0;
while(i < count){
Node node = userlinklist.findUser(i);
if(node == null){
i++;
continue;
}
try{
node.output.writeObject("用户列表");
node.output.flush();
node.output.writeObject(userlist);
node.output.flush();
}
catch(Exception e){
//System.out.println(e);
}
i++;
}
}
public void sendToAll(String msg){//发送消息给所有用户
int count = userlinklist.getCount();
int i = 0;
while(i < count){
Node node = userlinklist.findUser(i);
if(node == null){
i++;
continue;
}
try{
node.output.writeObject("聊天消息");
node.output.flush();
node.output.writeObject(msg);
node.output.flush();
}
catch(Exception e){
//System.out.println(e);
}
i++;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -