python - 请帮助我在 python 中进行套接字编程
问题描述
与服务器建立连接时出现问题。
服务器端:
import socket
import threading
import sys
ip = "let ip address of server, cant type real one for security purposes, example: 1.2.3.4"
port = 9999
def make_socket(ip, port):
global server
try:
server = socket.socket()
server.bind((ip, port))
except:
make_socket(ip, port)
def handle_client(conn, addr):
print(f"Connected with {addr}\n")
connected = True
while connected:
msg = conn.recv(1024).decode("utf-8")
if msg == "exit()":
connected = False
if len(msg) > 0:
print(f"CLIENT: {msg}")
if connected:
msg = input("You: ")
if len(msg) > 0:
conn.send(msg.encode("utf-8"))
conn.close()
def make_connection():
server.listen(2)
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"ACTIVE CONNECTIONS:{threading.activeCount() - 1}")
print("SERVER INITIATED.")
make_socket(ip, port)
make_connection()
客户端:
import socket
ip = "same address as written in server side, example: 1.2.3.4"
port = 9999
client = socket.socket()
client.connect((ip, port))
def send(msg):
message = msg.encode("utf-8")
client.send(message)
run = True
while run:
msg = input("You: ")
if msg == "exit()":
send(msg)
run = False
else:
send(msg)
print(f"Server: {client.recv(100).decode('utf-8')}")
它在同一台电脑上按预期运行。
但是当我在两台不同的电脑上运行客户端脚本和服务器脚本时,它们没有连接。即使地址相同。我必须在server.bind
and中输入服务器的 IP 地址client.connect
,对吗?他们两个应该是一样的,对吧?
解决方案
您传递给client.connect()
的 IP 地址应该是运行服务器的计算机的 IP 地址(如果它与运行客户端的计算机是同一台计算机,则可以直接传递127.0.0.1
,因为该地址始终表示 localhost)。对于bind()
呼叫,我建议传入''
(即空字符串)作为地址,以便您的服务器接受来自任何活动网络接口的传入连接。bind()
如果要将传入连接限制为仅通过与指定 IP 地址关联的本地网卡传入的连接,则只需传入显式 IP 地址即可。
推荐阅读
- cuda - 每个 SM 活动的线程块
- python - 在 Tensorflow 中,如何将一个张量添加到另一个形状不同的张量中?
- dynamic - 如何在设计时编写仅在运行时创建的组件
- c# - unity EditorWindow#Focus 无法触发 OnFocus
- c++ - std::vector 的容量会减少吗?
- asp.net - 如何在移动应用程序中修复服务器错误 500 web api
- rendering - 为什么启用混合时会出现此渲染问题?
- pandas - 在特定的值熊猫序列之后提取一行?
- excel - 不能用 R1C1 公式连接变量
- c++ - 为用户定义的类正确调用复制构造函数/赋值运算符