客户端没有从Server python接收数据

问题描述 投票:1回答:2

我是Python的新手。我正在写一个服务器程序和一个客户端程序。在此处,服务器扮演将数据分发到多个客户端的角色。它很棒。我的任务是使用server.py文件从服务器分发数据。无论何时客户想要它,他只需在他的笔记本电脑中执行clients.py并获得结果。但在这里,服务器开始分发数据。 ip,服务器使用的是127.0.1.1。它没有提供ip提供的网络。如何使用LAN提供的IP。当来自其他计算机的客户端执行clients.py文件时。它显示连接拒绝错误。请注意,我们都在局域网中连接。如何解决它并使客户端接收数据。

以下是客户代码示例:

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()
python python-3.x sockets client-server python-sockets
2个回答
1
投票

终于找到了答案

在'/ etc / hosts'文件内容中,我有一个IP地址映射为'127.0.1.1'到我的主机名。这导致名称解析得到127.0.1.1。我评论了这一行。现在它有效。我的局域网中的每个人都可以接收数据

服务器代码:

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()

客户代码:

import socket
import os
import time

s = socket.socket()  
host = '192.168.1.35' #my server ip 
port = 10016
print(host)


s.connect((host, port))
while True:
    print(s.recv(1024))
s.close() 

0
投票

配置局域网提供的IP到client.py(局域网中的IP如下:192.168.122.33)

host = 'ip provided by LAN'
© www.soinside.com 2019 - 2024. All rights reserved.