简体   繁体   English

将Java Server与Python客户端连接

[英]Connecting a Java Server with a Python Client

So here's the thing, I have a basic java server that sends back to the client what ever it receives from it. 事情就是这样,我有一个基本的Java服务器,它将从客户端接收到的内容发送回客户端。 The client is written in python. 客户端是用python编写的。 I'm able to make the first connection as in the server sends the client a message confirming the connection. 我能够建立第一个连接,因为服务器向客户端发送了一条确认连接的消息。 But when I want the client to send the server something is does nothing. 但是,当我希望客户端向服务器发送邮件时,什么也没做。 I'm not sure if the problem with the client not sending or the server not receiving. 我不确定客户端是否未发送或服务器未接收到问题。

Here's the code for the server: 这是服务器的代码:

    int portNumber = Integer.parseInt(args[0]);

    try ( 
        ServerSocket serverSocket = new ServerSocket(portNumber);
        Socket clientSocket = serverSocket.accept();
        PrintWriter outs =
            new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(clientSocket.getInputStream()));
    ) {

        String inputLine, outputLine;


        outputLine = "Hello socket, I'm server";
        outs.println(outputLine);
        outs.println("I' connected");
        while ((inputLine = in.readLine()) != null) {
             outputLine = inputLine;
            outs.println(outputLine);
            if (outputLine.equals("Bye."))
                break;

        }

    } catch (IOException e) {
        System.out.println("Exception caught when trying to listen on port "
            + portNumber + " or listening for a connection");
        System.out.println(e.getMessage());
    }
}  }

and here's the client : 这是客户:

import socket

HOST = "localhost"
PORT = 8080

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100

while True :  
    data = sock.recv(buffer_size)     
    print ('you recieved :' , data)
    test = input('send here\n')     
    sock.sendall(bytes(test, 'utf-8'))
    print ('you sent : ' , test)

In the Python client: Your prompt contains a \\n but the result from input does not? 在Python客户端中:您的提示包含\\n但是输入的结果不? Try adding a \\n to test before sending. 发送前,请尝试添加\\n进行test

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

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