简体   繁体   中英

Where is the error // why doesn't it work? (Java Chat program)

I wanted to write a UDP java chat program where I can send and receive messages to and from another person using this program. I figured out socket programming by my own (google search etc.), so I don't completely understand every single part. The basic idea is to read a random IP you want to chat with as a String, converting it into an IP and starting two threads, one for sending messages from port A and one for receiving messages at port B (the threads are used for being both able to send and recieve messages at the same time). Every thread has it's own class. So far, so good. Now both classes have the method run which are both in a big try-catch block. At the two catch blocks, I added several error messages, first "Test123" and then "Test456" so I can understand what happens when. When compiling the code, I can type in the IP (I tried localhost for testing). But when I type in the message, I should recieve the message "chat partner sent: ", but instead I don't get anything. Now both threads are in an infinite loop, so when I force the program to terminate (by pressing Ctrl+C (I run the .class via command)), I get the error message "Test123" before the program terminates. My questions are: Why don't I receive any message and why does the program throw "Test123" when I force the program to terminate? Where are my errors? Thanks in advance for helping. Here's the code:

import java.net.*;
import java.util.Scanner;

public class chat {
    static InetAddress IP;
    static int sPort=11111;
    static int rPort=11112;
    public static void main(String[] args) throws Exception{
        System.out.println("Zu welcher IP soll verbunden werden?");//"which IP do you want to connect with?"
        Scanner sc = new Scanner(System.in);
        String IPraw=sc.next(); //type in the IP address as String
        IP=InetAddress.getByName(IPraw); //converting the String into real IP address
        Thread sender = new sender();
        sender.start(); //start the sending thread
        Thread receiver = new receiver();
        receiver.start(); //start the receiving thread
    }
}
class sender extends Thread{
    public void run(){
        byte[] sendData = new byte[1024];
        Scanner scantext = new Scanner(System.in);
        try{
            DatagramSocket Socket = new DatagramSocket();
            while(true){
                String TextSend = scantext.next();
                sendData = TextSend.getBytes();
                DatagramPacket out = new DatagramPacket(sendData, sendData.length, chat.IP, chat.rPort);
                Socket.send(out);
            }
        }
        catch(Exception e){
        System.out.println("Test123");
        }
    }
}

class receiver extends Thread{
    public void run(){
        byte[] receiveData = new byte[1024];
        try{
            DatagramSocket socket = new DatagramSocket();
            while(true){
                DatagramPacket in = new DatagramPacket(receiveData, receiveData.length, chat.IP, chat.sPort);
                socket.receive(in);
                String message = new String(in.getData());
                System.out.println("Chatpartner sagt: " + message);//"partner said <message>"           
            }
        }
        catch(Exception e){
        System.out.println("Test456");
        }
    }
}

the sender thread is wating for you to insert some data on System.in (just type something). It is blocked here, on this line: String TextSend = scantext.next();

It appears that your application does not work because you are sending the data to different ports.

static int sPort=11111;
static int rPort=11112;

You need to send it to the same port (and in case of sending it to your own computer, you need to specify either your local ip-address , localhost or 127.0.0.1 ).

As for your first question

Why don't I receive any message

Are you connecting to 127.0.0.1 ? What exactly are your parameters?

As for your second question

why does the program throw "Test123" when I force the program to terminate?

because at that very moment you break the while-loop

try{
    DatagramSocket Socket = new DatagramSocket();
    while(true){
        String TextSend = scantext.next();
        sendData = TextSend.getBytes();
        DatagramPacket out = new DatagramPacket(sendData, sendData.length, chat.IP, chat.rPort);
        Socket.send(out);
    }
}

Terminating the application like that results in an exception.

You are sending on one port, and receiving on another. If your intention is for this code to send and receive its own message, those ports will need to be the same. If your intention is to actually chat with someone else (even with yourself on localhost), the other chat would have to receive on your send port and send on your receive port.

Also, what hexafraction said:

Don't catch exceptions and print next-to-useless messages. Use e.printStackTrace() instead.

That's where your error went, you caught it and printed your message instead

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