如何在Python中从客户端向服务器发送消息

7

我正在阅读两个Python 2.7.10中的程序,包括客户端和服务器。如何修改这些程序以便从客户端向服务器发送消息?

server.py:

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

client.py:

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 80              # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done
2个回答

13

TCP套接字是双向的。因此,在连接后,服务器和客户端之间没有区别,你只有一个流的两个端点:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
s.bind(('0.0.0.0', 12345))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   print c.recv(1024)
   c.close()                # Close the connection

以及客户端:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
s.connect(('localhost', 12345))
s.sendall('Here I am!')
s.close()                     # Close the socket when done

8
上面的回答出现了错误:TypeError: a bytes-like object is required, not 'str' 然而,以下代码对我有效:

server.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 3125
s.bind(('0.0.0.0', port))
print ('Socket binded to port 3125')
s.listen(3)
print ('socket is listening')

while True:
    c, addr = s.accept()
    print ('Got connection from ', addr)
    print (c.recv(1024))
    c.close()

client.py:

import socket

s = socket.socket()
port = 3125
s.connect(('localhost', port))
z = 'Your string'
s.sendall(z.encode())    
s.close()

提供错误的原因是由于新版本的Python引入了一些新功能。因此,您需要将字符串转换为字节,然后将字节解码为字符串。消息 = '你好,世界'字符串转字节 = bytes(消息, encoding='utf-8')之后,在另一端接收到您的消息(作为bytes_message),您可以通过以下方式将其转换为字符串字节转字符串 = str(bytes_message, encoding='utf-8')str()非常强大 :) - Strelok

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接