如何从Python服务器向Java客户端发送消息

时间:2019-02-07 12:38:13

标签: java python sockets

我已经制作了一个可以使用套接字从Java客户端接收字符串消息的python服务器,现在我想从python服务器向Java客户端发送字符串消息,请帮助我。我是Java新手,请帮助我! 这是Java代码:

public client(String address, int port) throws IOException {
    // establish a connection
    try {
        socket = new Socket(address, port);
        System.out.println("Connected");

        // takes input from terminal
        input = new DataInputStream(System.in);

        // sends output to the socket
        out = new DataOutputStream(socket.getOutputStream());
        System.out.print(input);

    } catch(UnknownHostException u) {
        System.out.println(u);
    }


    // string to read message from input
    String line = "";

    // keep reading until "Over" is input
    while (!line.equals("Over")) {
        try {
            line = br.readLine();
            out.writeUTF(line);
        } catch(IOException i) {
            System.out.println(i);
        }
    }

    // close the connection
    try {
        input.close();
        out.close();
        socket.close();
    } catch(IOException i) {
        System.out.println(i);
    }
}

public static void main(String args[]) throws IOException {
    client client = new client("127.0.0.1", 12345);
}

以下是将消息发送到Java客户端的python服务器代码:

 c, addr = s.accept()
 c.sendall('Thank you for connecting'.encode())

1 个答案:

答案 0 :(得分:0)

这里是链接: https://www.codejava.net/java-se/networking/java-socket-client-examples-tcp-ip 然后从那里编写代码:

InputStream input = socket.getInputStream();
byte[] data =…
input.read(data);

但是请检查该链接。