Python如何构建*real*ip地址的多客户端服务器
假设我在python中有一个多客户端服务器套接字和一个客户端套接字 服务器:(您不必阅读服务器的所有代码,只需知道它是一个多客户端服务器Python如何构建*real*ip地址的多客户端服务器,python,sockets,ip,Python,Sockets,Ip,假设我在python中有一个多客户端服务器套接字和一个客户端套接字 服务器:(您不必阅读服务器的所有代码,只需知道它是一个多客户端服务器 import socket, select CONNECTION_LIST = [] # list of socket clients RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2 PORT = 5000 server_socket = socket.socket(sock
import socket, select
CONNECTION_LIST = [] # list of socket clients
RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
RealServerIP = ? # I want to have a real server ip which would let me connect to the server from any computer around the globe...
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((RealServerIP, PORT))
server_socket.listen(10)
# Add server socket to the list of readable connections
CONNECTION_LIST.append(server_socket)
print "Chat server started on port " + str(PORT)
while 1:
# Get the list sockets which are ready to be read through select
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
#New connection
if sock == server_socket:
# Handle the case in which there is a new connection recieved through server_socket
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
#Some incoming message from a client
else:
# Data recieved from client, process it
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
# echo back the client message
if data:
sock.send(data)
# client disconnected, so remove from socket list
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
(示例来自)
和3个客户,这是你能想象到的最简单的客户:
import socket # imports module named 'socket'
RealServerIP = ? # I need your help here.... read the continuation
my_socket = socket.socket() # creates new socket named 'my_socket'
my_socket.connect((RealServerIP, 5000)) # connects to the server
my_socket.send(str) # sends string to the server
data = my_socket.recv(1024)
print data # prints data
my_socket.close()
我想检查我的服务器是否可以同时与这3个客户端通信,所以我想让我的服务器成为一个公共服务器,就像Facebook的web服务器一样,等等。
所以世界上任何一台计算机都可以连接到它
因此,我试图找出如何使用与本地主机无关的特定IP和端口在线存储python服务器套接字,我希望它是真实的!就像您知道的任何聊天/web服务器一样。如果您指的是用户连接到internet的IP,我不认为有办法通过
套接字
模块获取它,但是如果这有帮助的话,我可以使用请求
模块做同样的事情
import requests
def get_ip():
url = 'https://www.cmyip.com'
user_ip = requests.get(url).content.decode("utf-8").split("My IP Address is ")[1].split(" <a class=")[0]
return user_ip
导入请求
def get_ip():
url='1〕https://www.cmyip.com'
user_ip=requests.get(url).content.decode(“utf-8”).split(“我的ip地址是”)[1].split(“你需要绑定到你的ip地址而不是环回接口。或者在路由器/防火墙转发到服务器绑定到的任何地址/端口。谢谢。你能举个例子吗?”?