您好我正在尝试创建一个小型客户端服务器或服务器客户端聊天消息应用程序作为实验,并获得一些 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();
}
}
};
}