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

标签 python networking server client

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

服务器.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

客户端.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

最佳答案

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

关于python - 如何在python中从客户端向服务器发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227176/

相关文章:

linux - Socket服务器ip/端口问题

java - 如何让我的客户端与我的服务器对话?

javascript - 在服务器上部署 React App 时 MIME 类型检查失败

python - 如何在 Django 中默认 IntegerField

python - 在 Python 中分隔字符串和整数

python排序负数和/或十进制字母数字字符串

java - 适用于 Windows 的网络适配器

python - 使用两个版本的 Python (Windows) 安装 IPython

networking - Prolog 中的网络模块化优化

linux - 静态目录和文件设置755,是否可以上传执行恶意脚本?