两个套接字之间的套接字连接问题

时间:2018-07-09 13:38:06

标签: python-3.x sockets

我想创建一个套接字,以使用我选择的端口在客户端与服务器之间进行连接。我在下面收到错误代码。

客户端代码

import socket
import time
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 5555))
clientsocket.send('42.222,93457345345,0\n')
time.sleep(5)
clientsocket.send('42.222,93457345345,0\n')
time.sleep(5)
clientsocket.send('42.222,93457345345,0\n')
time.sleep(5)
clientsocket.send('42.222,93457345345,0\n')
time.sleep(5)

服务器端代码

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 5555))
serversocket.listen(5) # become a server socket, maximum 5 connections


while True:
    connection, address = serversocket.accept()
    buf = ''
    while True:
        buf = buf+connection.recv(5)
        if '\n' not in buf:
            continue
        else:
            while '\n' in buf:
                message_end=buf.find('\n')
                message=buf[:message_end]
                print (message)
                message.split(',')
                buf=buf[message_end+1:]

每当我运行该程序时,我都会得到此错误代码

客户端错误代码:

C:\Scripts\python.exe C:/Programs/Python/Python37-32/Lib/site-packages/GooMPy-master/client.py
Traceback (most recent call last):
  File "C:Programs/Python/Python37-32/Lib/site-packages/GooMPy-master/client.py", line 5, in <module>
    clientsocket.send('42.222,93457345345,0\n')
TypeError: a bytes-like object is required, not 'str'

Process finished with exit code 1

服务器端错误

Traceback (most recent call last):
  File "C:/Programs/Python/Python37-32/Lib/site-packages/GooMPy-master/server.py", line 12, in <module>
    buf = buf+connection.recv(5)
TypeError: can only concatenate str (not "bytes") to str

Process finished with exit code 1

1 个答案:

答案 0 :(得分:1)

您需要将数据(字符串)转换为字节。

用于文字:

clientsocket.send(b'42.222,93457345345,0\n')

或对于varialabes:

my_string = '42.222,93457345345,0\n'
clientsocket.send(my_string.encode('utf-8')

使用以下代码在服务器站点上解码

data = received_bytes.decode('utf-8')