Java 使用TCP的聊天程序:只有第一条消息到达另一端

Java 使用TCP的聊天程序:只有第一条消息到达另一端,java,swing,tcp,Java,Swing,Tcp,我在写一个TCP聊天程序 这是我的输出。 正如您所看到的,只有来自每个对等方的第一条消息到达了另一端。 病房上的第二条信息不显示。 这是我的全部代码。你可以运行它。我错在哪里 import java.io.*; import java.awt.*; import java.awt.event.*; import java.net.*; import javax.swing.*; class chattcp extends JFrame { public static void mai

我在写一个TCP聊天程序

这是我的输出。 正如您所看到的,只有来自每个对等方的第一条消息到达了另一端。 病房上的第二条信息不显示。

这是我的全部代码。你可以运行它。我错在哪里

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;

class chattcp extends JFrame {
    public static void main(String args[]){
        chattcp peer1=new chattcp("peer1",9999,9998);
        chattcp peer2=new chattcp("peer2",9998,9999);       
    }

    chattcp(String name,int lis,int snd){
        this.setVisible(true);
        this.setTitle(name);
        this.setLayout(null);
        this.setSize(500,500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TextField tf=new TextField();
        this.add(tf);
        tf.setBounds(10,20,100,40);

        TextArea ta=new TextArea();
        this.add(ta);
        ta.setBounds(10,80,400,400);
        ta.setEditable(false);
        ta.setFont(ta.getFont().deriveFont(20f));
        Button b=new Button("send");
        this.add(b);
        b.setBounds(130,20,60,40);
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent a){
                try{
                    String s= tf.getText();
                    Socket skt=new Socket("localhost",snd);
                    DataOutputStream dos= new DataOutputStream(skt.getOutputStream());
                    dos.writeUTF(s);
                    ta.append("You :"+s+"\n");
                    tf.setText("");
                }
                catch(IOException e){
                    e.printStackTrace();
                }
            }
        });

        Thread receive=new Thread() {
                    public void run(){
                      try{
                        ServerSocket ser=new ServerSocket(lis);
                        Socket sktt=ser.accept();
                        DataInputStream dis= new DataInputStream(sktt.getInputStream());
                        while (true){
                            String s= dis.readUTF();
                            ta.append("Friend : "+s+"\n");
                        }
                      }catch(IOException e){e.printStackTrace();}
                    }
                };
        receive.start();

    }
}

每次单击“发送”按钮时,都会创建一个新套接字并尝试连接

问题是,一旦您发送了一些东西,就会创建套接字,serversocket接受并启动循环

当您现在编写第二条消息时,您正在创建一个新套接字,而循环仍在尝试从旧套接字读取OutputStream

解决问题的一个方法是在每次读取后关闭serversocket,并在每次迭代中创建一个新的serversocket:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;

public class chattcp extends JFrame {

public static void main(String args[]) {
    chattcp peer1 = new chattcp("peer1", 9999, 9998);
    chattcp peer2 = new chattcp("peer2", 9998, 9999);
}

chattcp(String name, int lis, int snd) {
    this.setVisible(true);
    this.setTitle(name);
    this.setLayout(null);
    this.setSize(500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    TextField tf = new TextField();
    this.add(tf);
    tf.setBounds(10, 20, 100, 40);

    TextArea ta = new TextArea();
    this.add(ta);
    ta.setBounds(10, 80, 400, 400);
    ta.setEditable(false);
    ta.setFont(ta.getFont().deriveFont(20f));
    Button b = new Button("send");
    this.add(b);
    b.setBounds(130, 20, 60, 40);
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent a) {
            try {
                String s = tf.getText();
                Socket skt = new Socket("localhost", snd);
                DataOutputStream dos = new DataOutputStream(skt.getOutputStream());
                dos.writeUTF(s);
                ta.append("You :" + s + "\n");
                tf.setText("");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    Thread receive = new Thread() {
        public void run() {
            try {
                while (true) {
                    ServerSocket ser = new ServerSocket(lis);
                    Socket sktt = ser.accept();
                    DataInputStream dis = new DataInputStream(sktt.getInputStream());

                    String s = dis.readUTF();
                    ta.append("Friend : " + s + "\n");

                    ser.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    receive.start();

}
}

一个更好的解决方案是,当你发送东西时,不要总是创建一个新的套接字,但是我很懒,而且这个解决方案更容易编辑你的代码,所以我只是使用了它。

你每次点击发送按钮都在创建一个新的连接,但是服务器只监听一次

一个简单的答案是保存套接字并重用它

class chattcp extends JFrame {
    public static void main(String args[]){
        chattcp peer1=new chattcp("peer1",9999,9998);
        chattcp peer2=new chattcp("peer2",9998,9999);
    }

    Socket skt = null;

    chattcp(String name,int lis,int snd){
        this.setVisible(true);
        this.setTitle(name);
        this.setLayout(null);
        this.setSize(500,500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TextField tf=new TextField();
        this.add(tf);
        tf.setBounds(10,20,100,40);

        TextArea ta=new TextArea();
        this.add(ta);
        ta.setBounds(10,80,400,400);
        ta.setEditable(false);
        ta.setFont(ta.getFont().deriveFont(20f));
        Button b=new Button("send");
        this.add(b);
        b.setBounds(130,20,60,40);
        b.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent a){
                try{
                    if (skt == null) {
                        skt = new Socket("localhost",snd);                        
                    }

                    DataOutputStream dos= new DataOutputStream(skt.getOutputStream());

                    String s= tf.getText();
                    dos.writeUTF(s);
                    ta.append("You :"+s+"\n");
                    tf.setText("");
                }
                catch(IOException e){
                    e.printStackTrace();
                }
            }
        });

        Thread receive=new Thread() {
                    public void run(){
                      try{
                        ServerSocket ser=new ServerSocket(lis);
                        Socket sktt=ser.accept();
                        DataInputStream dis= new DataInputStream(sktt.getInputStream());
                        while (true){
                            String s= dis.readUTF();
                            ta.append("Friend : "+s+"\n");
                        }
                      }catch(IOException e){e.printStackTrace();}
                    }
                };
        receive.start();
    }
}