将Java服务器与Python客户端连接

时间:2017-03-08 09:42:22

标签: java python client-server python-sockets

所以这就是问题,我有一个基本的java服务器,它会向客户端发送从它接收的内容。客户端是用python编写的。我能够在服务器中建立第一个连接,向客户端发送确认连接的消息。但是,当我希望客户端发送服务器时,什么都没做。我不确定客户端是否发送问题或服务器没有收到问题。

以下是服务器的代码:

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

这是客户:

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)

1 个答案:

答案 0 :(得分:0)

在Python客户端中: 您的提示包含\n,但输入的结果不是?在发送之前尝试将\n添加到test