【问题标题】:chat between server and a client in different computers connected to the same wifi using python sockets使用python套接字连接到同一个wifi的不同计算机中的服务器和客户端之间的聊天
【发布时间】:2014-08-18 01:50:35
【问题描述】:

我正面临一些问题,因为我正在努力通过 wifi 扩展一个简单的聊天程序。 我将在不同系统上运行的两个程序命名为客户端和服务器,认为它们不执行它们的典型功能。 服务器程序正确显示客户端发送的消息,但是一旦服务器发送消息,客户端程序就没有收到它。我检查了IP,一切都很好。客户端和服务器代码也相似,唯一的区别在于谁先发送消息(根据我的程序是客户端)。 我需要尽快帮助。 提前致谢。

这是我的客户程序

from socket import *
import sys
import time
TO_ADDR=('192.168.1.101',8135)
hostname=gethostbyname('0.0.0.0')
LOCAL_ADDR=(hostname,8138)
MSG_LEN=1000 
fd=socket(AF_INET, SOCK_DGRAM)
fd.bind(LOCAL_ADDR)
s=('',)
msg=''
def recv():
    s=fd.recvfrom(MSG_LEN)
    print '\n',s[0]
    print '\n'
    return s[0]
def send(msg):
    fd.connect(('192.168.1.101',8135))
    fd.sendto(msg,TO_ADDR)

while msg!='stop' or s!='stop':
    print '\n'
    msg=raw_input('Enter your message:')
    send(msg)
    s=recv()
    print '\n',s[0]

这是我的服务器程序

from socket import *
s=('',)
msg=''
TO_ADDR=('198.168.1.103',8138)
hostname=gethostbyname('0.0.0.0')
LOCAL_ADDR=(hostname,8135)
MSG_LEN=1000
fd=socket(AF_INET,SOCK_DGRAM)
fd.bind(LOCAL_ADDR)

def recv():
s=fd.recvfrom(MSG_LEN)
print '\n',s[0]
print '\n'
return s[0]
def send(msg):
fd.connect(('198.168.1.103',8138))
fd.sendto(msg,TO_ADDR)
fd.close()


while s[0]!='stop' or msg!='stop':
s=recv()
msg=raw_input('Enter your message:')
send(msg)

【问题讨论】:

    标签: python sockets networking wifi send


    【解决方案1】:

    UDP(你正在使用SOCK_DGRAM)是一个无状态协议。因此,您无法像在代码中尝试那样从服务器“连接”到客户端。

    见:UDP Communication

    你必须这样做:

    data, addr = fd.recvfrom(1024)
    fd.sendto(data, addr)
    

    您可以将 recv() 函数更改为:

    def recv():
        data, addr = fd.recvfrom(MSG_LEN)
        print '\n',s[0]
        print '\n'
        return data, addr
    

    还有你的send() 函数:

    def send(msg, addr):
        fd.sendto(msg, addr)
    

    你的代码的最后一部分是:

    while s[0]!='stop' or msg!='stop':
        data, addr = recv()
        msg = raw_input('Enter your message:')
        send(msg, addr)
    

    见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多