Search code examples
pythonsocketsgoserverclient

How to send strings between python and go


I am trying to understand how to interact with python socket server meant for python socket client but in go

please rewrite python client in go language with same functionality without changing server code, that should be enough for me to understand how to do it

server:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = '127.0.0.1'
port = 5556

server.bind((host,port))
server.listen()
client, adress = server.accept()
#1
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#2
client.send("send2".encode('utf-8'))
#3
variable2 = client.recv(4096).decode('utf-8')
print(variable2)
#4
client.send("send4".encode('utf-8'))

client:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = '127.0.0.1'
port = 5556

client.connect((host, port))


#1
client.send("send1".encode('utf-8'))
#2
variable1 = client.recv(4096).decode('utf-8')
print(variable1)
#3
client.send("send3".encode('utf-8'))
#4
variable2 = client.recv(4096).decode('utf-8')
print(variable2)

Solution

  • Close the connection to terminate the stream of data from the server to the client:

    ⋮
    client.send("text1".encode('utf-8'))
    client.close()
    

    Read to EOF in the client program:

    ⋮
    message, err := io.ReadAll(conn)                
    checkError(err)
    fmt.Println(string(message))