'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. Here are some outputs:

image 1

image 2

Here is the server code (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):

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


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 idanz