gpt4 book ai didi

java套接字线程正在工作但没有消息

转载 作者:行者123 更新时间:2023-12-01 18:54:28 26 4
gpt4 key购买 nike

您好,我正在尝试创建一个小型客户端服务器或服务器客户端聊天消息应用程序作为实验,并获得一些 java 套接字知识和经验。我在发送和接收消息时遇到问题。我确实获得了连接,并且线程看起来正在运行,但它不会相互发送或接收消息。我不确定连接一旦连接是否会自动关闭,但我知道我做错了什么,但我似乎找不到它。如果你能帮助我那就太好了。代码如下

<小时/>

服务器:

public class ServerGUI extends JFrame implements KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
/*private JButton sendButton = new JButton("send");
private JButton connectButton = new JButton("Connect");
private JButton disconnectButton = new JButton("Disconnect");*/
private JTextField textMessage = new JTextField();
private JLabel connectMessageLabel = new JLabel("Waiting for Client");
private JTextArea messageTextArea = new JTextArea();
private JPanel buttonPanel = new JPanel();
private JPanel messageLabelPanel = new JPanel();
private JPanel messageTextAreaPanel = new JPanel();
private JPanel content = new JPanel();
private static String thisName= "<Me> ";
private static String friendLabel= "<My Friend> ";
private static JFrame serverFrame = new JFrame();
private int port= 0;
private String clientMessage=null;
private String myMessage=null;
private ServerSocket listenSocket;
private Socket connection;
private InputStream inStream;
private DataInputStream inDataStream;
private OutputStream outStream;
private DataOutputStream outDataStream;
private Thread runChatServer;

//----------------------------------------------------------------------------------------------
//-------------------------serverGui------------------------------------------------------------
@SuppressWarnings("deprecation")
public ServerGUI(int port){
this.port = port;
messageLabelPanel.setLayout(new GridLayout(1, 1, 1, 1));
messageLabelPanel.add(connectMessageLabel);
buttonPanel.setLayout(new GridLayout(1, 1, 1, 1));
//buttonPanel.add(connectButton);
//buttonPanel.add(sendButton);
buttonPanel.add(textMessage);
textMessage.addKeyListener(this);
textMessage.setForeground(Color.BLACK);
messageTextAreaPanel.setLayout(new BorderLayout(1, 1));
messageTextAreaPanel.add(buttonPanel, BorderLayout.SOUTH);
messageTextAreaPanel.add(messageLabelPanel,BorderLayout.NORTH);
messageTextAreaPanel.add(new JScrollPane(messageTextArea),BorderLayout.CENTER);
messageTextArea.setDisabledTextColor(Color.BLACK);
messageTextArea.enable(false);
content.setLayout(new GridLayout(1, 1, 1, 1));
content.add(messageTextAreaPanel);
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
serverFrame.setContentPane(content);
serverFrame.pack();
serverFrame.setSize(450,550);
serverFrame.setLocationRelativeTo(null);
serverFrame.setVisible(true);
serverFrame.setTitle("Chat Server");
serverFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

startServer();
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void startServer(){
System.out.println("startServer");
try{
listenSocket = new ServerSocket(port);
System.out.println("Waiting for client");
connection = listenSocket.accept();
System.out.println("Client Found");
connectMessageLabel.setText("Client Found");
runChatServer = new Thread(serverListeningAndChatting);
runChatServer.start();
}
catch (Exception ex){

System.out.println("No Connection Found");
connectMessageLabel.setText("No Connection Found");
}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------listening------------------------------------------------------------
public void listening(){
System.out.println("listening");
try{
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
clientMessage = inDataStream.readUTF();
if (clientMessage!= null){
messageTextArea.append(clientMessage + "\n");
clientMessage = null;
}
}catch(Exception ex){System.out.println(ex);}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------sendMessage------------------------------------------------------------
public void sendMessage(){
System.out.println("sendMessage");
try{
outStream = connection.getOutputStream();
outDataStream = new DataOutputStream(outStream);

if (myMessage!=null){
outDataStream.writeUTF(myMessage);
myMessage=null;
}
}catch(Exception ex){System.out.println("Message Failed");}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER){
myMessage = friendLabel+ textMessage.getText();
messageTextArea.append(thisName+textMessage.getText() +"\n");
textMessage.setText("");
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

//-----------------------------------------------------------------------------------------------------
//-------------------------------main------------------------------------------------------------
public static void main (String args[]){
new ServerGUI(8901);
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------run------------------------------------------------------------
public Runnable serverListeningAndChatting = new Runnable(){
public void run() {
while (true){
System.out.println("Running");
listening();
sendMessage();
}
}
};

}
<小时/>

客户:

public class ClientGUI extends JFrame implements KeyListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField textMessage = new JTextField();
private JLabel connectMessageLabel = new JLabel("Connection failed or no Server is available");
private JTextArea messageTextArea = new JTextArea();
private JPanel buttonPanel = new JPanel();
private JPanel messageLabelPanel = new JPanel();
private JPanel messageTextAreaPanel = new JPanel();
private JPanel content = new JPanel();
private static String thisName= "<Me> ";
private static String friendLabel= "<My Friend> ";
private static JFrame clientFrame = new JFrame();
private int port =0;
private String remoteMachine =null;
private String clientMessage=null;
private String myMessage=null;
private Socket connection;
private InputStream inStream;
private DataInputStream inDataStream;
private OutputStream outStream;
private DataOutputStream outDataStream;
private Thread runChatClient;
//-----------------------------------------------------------------------------------------------------
//-------------------------------ClientGUI------------------------------------------------------------

@SuppressWarnings("deprecation")
public ClientGUI(String remoteMachine, int port){
this.port= port;
this.remoteMachine = remoteMachine;
messageLabelPanel.setLayout(new GridLayout(1, 1, 1, 1));
messageLabelPanel.add(connectMessageLabel);
buttonPanel.setLayout(new GridLayout(1, 1, 1, 1));
//buttonPanel.add(connectButton);
//buttonPanel.add(sendButton);
buttonPanel.add(textMessage);
textMessage.addKeyListener(this);
textMessage.setForeground(Color.BLACK);
messageTextAreaPanel.setLayout(new BorderLayout(1, 1));
messageTextAreaPanel.add(buttonPanel, BorderLayout.SOUTH);
messageTextAreaPanel.add(messageLabelPanel,BorderLayout.NORTH);
messageTextAreaPanel.add(new JScrollPane(messageTextArea),BorderLayout.CENTER);
messageTextArea.setDisabledTextColor(Color.BLACK);
messageTextArea.enable(false);
content.setLayout(new GridLayout(1, 1, 1, 1));
content.add(messageTextAreaPanel);
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
clientFrame.setContentPane(content);
clientFrame.pack();
clientFrame.setSize(450,550);
clientFrame.setLocationRelativeTo(null);
clientFrame.setVisible(true);
clientFrame.setTitle("Chat Client");
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

startClient();

}

//-----------------------------------------------------------------------------------------------------
//-------------------------------startClient------------------------------------------------------------
public void startClient(){
System.out.println("startClient");
try{
System.out.println("Connecting to Server");
connection = new Socket(remoteMachine, port);
System.out.println("Server Found");
connectMessageLabel.setText("Server Found");
runChatClient = new Thread(clientListeningAndChatting);
runChatClient.start();
}
catch (Exception ex){
System.out.println("No Connection Found");
connectMessageLabel.setText("No Connection Found");
}

}
//-----------------------------------------------------------------------------------------------------
//-------------------------------keyPressed------------------------------------------------------------
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER){
myMessage = friendLabel+ textMessage.getText();
messageTextArea.append(thisName+textMessage.getText() +"\n");
textMessage.setText("");
}
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------listening------------------------------------------------------------
public void listening(){
System.out.println("listening");
try{
inStream = connection.getInputStream();
inDataStream = new DataInputStream(inStream);
clientMessage = inDataStream.readUTF();
if (clientMessage!= null){
messageTextArea.append(clientMessage + "\n");
clientMessage = null;
}
}catch(Exception ex){System.out.println("Disconnected");}
}
//-----------------------------------------------------------------------------------------------------
//-------------------------------sendMessage------------------------------------------------------------
public void sendMessage(){
System.out.println("sendMessage");
try{
outStream = connection.getOutputStream();
outDataStream = new DataOutputStream(outStream);
if (myMessage!=null){
outDataStream.writeUTF(myMessage);
myMessage=null;
}
}catch(Exception ex){System.out.println("Message Failed");}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
//-----------------------------------------------------------------------------------------------------
//-------------------------------main------------------------------------------------------------
public static void main (String args[]){
new ClientGUI(null, 8901);
}

//-----------------------------------------------------------------------------------------------------
//-------------------------------run------------------------------------------------------------
public Runnable clientListeningAndChatting = new Runnable(){

public void run() {
System.out.println("Running");
while (true){
listening();
sendMessage();
}
}
};
}

最佳答案

声明

listenSocket.accept();

是一个阻塞调用,正在阻塞EDT。此和任何其他网络访问调用应由 SwingWorker 处理。 。由于 Swing 是单线程的,因此无法处理任何事件,因此客户端和服务器之间无法交换消息。

Thread 上使用 SwingWorker — 它负责处理 GUI 交互任务。

关于java套接字线程正在工作但没有消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14572522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com