简体   繁体   English

服务器向客户端套接字发送消息

[英]Server send message to client Sockets

I started working with sockets this week and I'm having a hard time.这周我开始使用套接字,但我遇到了困难。 My goal is when the client sent a message the server responded with a notification.我的目标是当客户端发送消息时,服务器以通知进行响应。 On the client side sending to the server has no problem, but when the server sends to the client nothing appears.在客户端发送到服务器没有问题,但是当服务器发送到客户端时什么也没有出现。 Can anybody help me with this problem?有人可以帮我解决这个问题吗?

Client:客户:

    Thread thread = new Thread(new myServerThread());
    thread.start();

class myServerThread implements Runnable {
    Socket socket;
    ServerSocket serverSocket;
    InputStreamReader inputStreamReader;
    BufferedReader bufferedReader;
    String message;
    Handler handler = new Handler();

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(5000);
            while (true){
                socket = serverSocket.accept();
                inputStreamReader = new InputStreamReader(socket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader);
                message = bufferedReader.readLine();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), message,Toast.LENGTH_LONG).show();
                        }
                    });
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
}

SERVER:服务器:

 String EMAIL = "Email";

   try {        
       serverSocket = new ServerSocket(6000);
       while(true){
       socket = serverSocket.accept();
       inputStreamReader = new InputStreamReader(socket.getInputStream());
       bufferedReader = new BufferedReader(inputStreamReader);
       email = bufferedReader.readLine();


       System.out.println(email);

       if(email.equals(EMAIL)){
           jTextArea1.setText(email);
           try {
            socket = new Socket("localHost", 5000);
            PrintWriter  printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.write(message);
            printWriter.flush();
            printWriter.close();
            System.out.println("connected");


        } catch (IOException e) {
            e.printStackTrace();
        }

       }else{
       }

       }

   } catch (IOException ex) {
   }
    etEmail = findViewById(R.id.etvEmail);

First the short answer: Your Java codes are both working almost fine.首先是简短的回答:您的 Java 代码几乎都可以正常工作。

Anyway, you should always test your application against another program that is known to be OK.无论如何,您应该始终针对另一个已知正常的程序测试您的应用程序。 By testing one self-written program against another fresh self-written program, it is difficult to say which of both is broken.通过将一个自编程序与另一个新的自编程序进行测试,很难说两者中的哪一个被破坏了。 It seems that you are testing it with some GUI (Android?).似乎您正在使用某些 GUI(Android?)对其进行测试。 Transforming the relevant part to a simple console application which you run on a regular PC makes troubleshooting much easier.将相关部分转换为您在普通 PC 上运行的简单控制台应用程序,可以使故障排除更加容易。

So let me show how I checked your code on my Linux laptop:那么让我展示一下我是如何在我的 Linux 笔记本电脑上检查你的代码的:

First copy your "client" code into a "Hello-World" template.首先将您的“客户端”代码复制到“Hello-World”模板中。 I added some debug messages and a loop which allows the client to receive more than one single line of text:我添加了一些调试消息和一个允许客户端接收多行文本的循环:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            try
            {
                serverSocket = new ServerSocket(5000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);
                    String message = bufferedReader.readLine();
                    while (message!=null)
                    {
                        System.out.println("Received:" + message);
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}

I started the "client" and opened another command window to open a network connection with Netcat and send two lines of text:我启动了“客户端”并打开另一个命令窗口以打开与 Netcat 的网络连接并发送两行文本:

nc localhost 5000
Hallo
Test

The related output of the "client" program was: “客户端”程序的相关输出是:

Accepting...
Connected...
Received:Hallo
Received:Test
Closing...
Accepting...

So the "client" part is running fine obviously.所以“客户端”部分显然运行良好。

Next I copied your "server" code into a "Hello World" template:接下来,我将您的“服务器”代码复制到“Hello World”模板中:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

class Main
{

    static class myServerThread implements Runnable
    {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String message;

        @Override
        public void run()
        {
            String EMAIL = "Email";

            try
            {
                serverSocket = new ServerSocket(6000);
                while (true)
                {
                    System.out.println("Accepting...");
                    socket = serverSocket.accept();
                    System.out.println("Connected...");
                    inputStreamReader = new InputStreamReader(socket.getInputStream());
                    bufferedReader = new BufferedReader(inputStreamReader);

                    String message = bufferedReader.readLine();
                    while (message != null)
                    {
                        System.out.println("Received:" + message);

                        if (message.equals(EMAIL))
                        {
                            System.out.println("Sending...");
                            try
                            {
                                socket = new Socket("localHost", 5000);
                                PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                                printWriter.write(message);
                                printWriter.flush();
                                printWriter.close();
                                System.out.println("sending done");

                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }

                        }
                        message = bufferedReader.readLine();
                    }
                    System.out.println("Closing...");
                    socket.close();
                }
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        Thread thread = new Thread(new myServerThread());
        thread.start();
    }
}

Again I added some debug messages and a loop, so the server can receive multiple lines of text.我再次添加了一些调试消息和一个循环,因此服务器可以接收多行文本。 Since this Java program handles two connections, I had to open two command windows.由于这个 Java 程序处理两个连接,我不得不打开两个命令窗口。

In the first command window I tell NetCat to accept (listen) connection on port 5000. That is where your "server" will send the "Email" message to:在第一个命令窗口中,我告诉 NetCat 接受(侦听)端口 5000 上的连接。这是您的“服务器”将“电子邮件”消息发送到的地方:

nc -lp 5000

In the second command window I tell Netcat to connect to your "server" on port 6000, then I send two lines of text and then I press Ctrl-C to stop it:在第二个命令窗口中,我告诉 Netcat 连接到端口 6000 上的“服务器”,然后发送两行文本,然后按 Ctrl-C 停止它:

nc localhost 6000
Test
Email
^C

The related output of the "server" program is: “服务器”程序的相关输出是:

Accepting...
Connected...
Received:Test
Received:Email
Sending...
sending done
Closing...
Accepting...

And my listening Netcat in the other (first) command windows produced this output:我在其他(第一个)命令窗口中监听 Netcat 产生了这个输出:

stefan@stefanpc:/hdd/stefan$ nc -lp 5000
Emailstefan@stefanpc:/hdd/stefan$ 

So everything looks fine on my machine.所以在我的机器上一切正常。 Beside one small detail: There is no line break after the "Email" that your "server" sends to the client (in this case NetCat).除了一个小细节:在您的“服务器”发送给客户端(在本例中为 NetCat)的“电子邮件”之后没有换行符。 So the fix is simple:所以修复很简单:

printWriter.write(message+"\n"); 

This final line break is required because your client consumes the input by readLine() .最后一个换行符是必需的,因为您的客户端通过readLine()使用输入。

NetCat is a very helpful tool to test plain text TCP socket communication. NetCat 是测试纯文本 TCP 套接字通信的非常有用的工具。 It is included in all Linux distributions.它包含在所有 Linux 发行版中。 If you have difficulties to find a Windows executable, then take it from my homepage: http://stefanfrings.de/avr_tools/netcat-win32-1.12.zip如果您在查找 Windows 可执行文件时遇到困难,请从我的主页获取它: http : //stefanfrings.de/avr_tools/netcat-win32-1.12.zip

Please comment if that was helpful to you.如果这对您有帮助,请发表评论。

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

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