Python使用套接字通过局域网连接

时间:2018-02-08 19:49:25

标签: python sockets

我正在尝试通过LAN在两台计算机之间发送消息。由于某种原因,客户端挂起,不知道为什么。

服务器:

#echo server
import socket

HOST = '192.168.1.135'                  
PORT = 50017       # port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
conn.send("Hello Client")
conn.send("How are you")
conn.close()
print("Connection", addr, "Closed")

客户端:

import socket

HOST = '192.168.1.135'    # The remote host
PORT = 50017          # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while 1:
    data = s.recv(1024)
    if not data: break
    print(data)
s.close()

1 个答案:

答案 0 :(得分:0)

简单的str-bytes问题。

服务器:

import socket

HOST = '192.168.1.135'                  
PORT = 50017       # port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
conn.send("Hello Client".encode())
conn.send("How are you".encode())
conn.close()
print("Connection", addr, "Closed")

客户

import socket

HOST = '192.168.1.135'    # The remote host
PORT = 50017          # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while 1:
    data = s.recv(1024)
    if not data: break
    print(data.decode())
s.close()