简体   繁体   中英

Chat program using TCP : Only first message reaches other end

I was writing a TCP chat program.

Here is my output. As you can see only first message from each peer is reaching the other end. Second message on wards are not displayed. 在此处输入图片说明

Here is my full code. You can run it. Where am I wrong?

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();

    }
}

Everytime you click your send button you create a new socket and try to connect.

The problem is, once you send something, the socket is created, the serversocket accepts and starts the loop.

When you now write the second message, you are creating a new socket while the loop is still trying to read from the OutputStream from the old socket.

one solution to your problem is to close the serversocket after each read and create a new serversocket each iteration:

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();

}
}

a better solution would be to not always create a new socket, when you send something, but i am lazy and this solution is easier to edit your code to, so i just used it.

You are creating a new connection every time that you click on the send button, but the Server only listen one time.

One simple answer is to save the Socket e reuse it.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM