简体   繁体   English

如何将字符串从 java 客户端发送到 python 服务器

[英]How to send a string from java client to python server

I'm sending strings to Python server.py from client.java , but there is some error in the string format while receiving into the server.我正在从client.java向 Python server.py发送字符串,但是在接收到服务器时字符串格式存在一些错误。 Here are some outputs:以下是一些输出:

图片 1

图 2

Here is the server code (server.py):这是服务器代码(server.py):

import socket

my_con = True

s = socket.socket()
host = 'localhost'
port = 1223

s.bind((host,port))
s.listen(5)

c,addr = s.accept()

print "got connection from",addr

while my_con:
    msg = c.recv(1024)
    print msg

    if msg == "quit":
        c.close()
        my_con = false

Client code (client.java):客户端代码(client.java):

// File Name GreetingClient.java
import java.net.*;
import java.io.*;
import java.util.*;

public class client {

    public static void main(String [] args) {
        BufferedReader br = new BufferedReader(new 
                InputStreamReader(System.in));

        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        boolean mycon = true;
        try {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, port);

            System.out.println("Just connected to " + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            while (mycon){

            String s_to_send = br.readLine();   

            System.out.println("sending " + s_to_send);

            out.writeUTF(s_to_send);
            }

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

Struggled with it as well and wanted to post for knowledge sharing - the recv function of python returns bytes, what needed to be decoded to UTF-8 string, so the only needed change is msg.decode("utf-8") when printing.也为此苦苦挣扎并希望发布知识共享 - python 的recv function 返回字节,需要解码为 UTF-8 字符串,因此打印时唯一需要的更改是msg.decode("utf-8")

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

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