简体   繁体   English

错误在哪里//为什么不起作用? (Java聊天程序)

[英]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. 我想编写一个UDP Java聊天程序,可以在其中使用该程序与其他人收发消息。 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). 基本思想是读取要作为字符串聊天的随机IP,将其转换为IP并启动两个线程,一个用于从端口A发送消息,一个用于在端口B接收消息(线程用于都能够同时发送和接收消息)。 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. 现在,这两个类都具有运行方法,它们都在一个较大的try-catch块中。 At the two catch blocks, I added several error messages, first "Test123" and then "Test456" so I can understand what happens when. 在这两个catch块中,我添加了一些错误消息,首先是“ Test123”,然后是“ Test456”,因此我可以理解什么时候发生。 When compiling the code, I can type in the IP (I tried localhost for testing). 编译代码时,我可以输入IP(我尝试使用localhost进行测试)。 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. 现在,两个线程都处于无限循环中,因此当我强制程序终止(通过按Ctrl + C(我通过命令运行.class))时,在程序终止之前会收到错误消息“ Test123”。 My questions are: Why don't I receive any message and why does the program throw "Test123" when I force the program to terminate? 我的问题是:为什么当我强制程序终止时,为什么我没有收到任何消息以及为什么程序会抛出“ Test123”? 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). 发送方线程希望您在System.in上插入一些数据(只需键入一些内容)。 It is blocked here, on this line: String TextSend = scantext.next(); 在此处的此行被阻止: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 ). 您需要将其发送到同一端口(如果要发送到您自己的计算机,则需要指定local ip-addresslocalhost127.0.0.1 )。

As for your first question 至于你的第一个问题

Why don't I receive any message

Are you connecting to 127.0.0.1 ? 您要连接到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 因为那一刻你打破了while循环

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. 如果您打算与其他人(即使您自己在localhost上)进行实际聊天,则其他聊天必须在您的发送端口上接收,并在您的接收端口上发送。

Also, what hexafraction said: 另外,hexafraction表示:

Don't catch exceptions and print next-to-useless messages. 不要捕获异常并打印下一个无用的消息。 Use e.printStackTrace() instead. 请改用e.printStackTrace()。

That's where your error went, you caught it and printed your message instead 那是您出错的地方,您抓住了它并打印了您的消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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