我是Python的新手。我正在编写服务器程序和客户端程序。在这里,服务器扮演着将数据分发到多个客户端的角色。效果很好。我的任务是使用server.py文件从服务器分发数据。每当有任何客户需要时,他只要在笔记本电脑中执行client.py并获取结果即可。但是在这里,服务器开始分发数据。 IP,服务器使用的是127.0.1.1。它不采取网络提供的IP。如何使用局域网提供的IP。当其他计算机上的客户端执行client.py文件时。它显示连接拒绝错误。请注意,我们都连接在LAN中。如何解决它并使客户接收数据。
这是示例客户端代码:
import socket
import os
from threading import Thread
import socket
import time
s = socket.socket()
host = '127.0.1.1'
port = 10016
print(host)
s.connect((host, port))
while True:
print(s.recv(1024))
s.close()
示例服务器代码:
import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.gethostname()
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = "Hi Steven!!!" + timestamp
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
答案 0 :(得分:1)
最后找到答案
在“ / etc / hosts”文件内容中,我有一个IP地址,其主机名映射为“ 127.0.1.1”。这导致名称解析得到127.0.1.1。我评论了这一行。现在可以了。我的局域网中的每个人都可以接收数据
服务器代码:
git blame
客户代码:
import socket
import os
from threading import Thread
import thread
import threading
import time
import datetime
def listener(client, address):
print ("Accepted connection from: ", address)
with clients_lock:
clients.add(client)
try:
while True:
client.send(a)
time.sleep(2)
finally:
with clients_lock:
clients.remove(client)
client.close()
clients = set()
clients_lock = threading.Lock()
host = socket.gethostname() # it gets ip of lan
port = 10016
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
client, address = s.accept()
timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
a = "Hi Steven!!!" + timestamp
th.append(Thread(target=listener, args = (client,address)).start())
s.close()
答案 1 :(得分:0)
配置LAN提供给client.py的IP(LAN中的IP像这样:192.168.122.33)
host = 'ip provided by LAN'