马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Robot_Steve 于 2022-5-2 10:00 编辑
我把代码放到上面,看看能不能实现局域网通讯:
两台不同的电脑实现通讯
A电脑(服务端):from socket import *
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connnecting from:', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
#tcpCliSock.send('[%s] %s' %(bytes(ctime(),'utf-8'),data))
tcpCliSock.send(('%s' % (data)).encode())
print(data.decode('utf-8'))
data1 = input('>')
# data = str(data)
if not data1:
break
tcpCliSock.send(data1.encode())
data1 = tcpCliSock.recv(BUFSIZ)
if not data1:
break
print(data1.decode('utf-8'))
tcpCliSock.close()
B电脑(客户端):from socket import *
HOST = '127.0.0.1' # or 'localhost'
PORT = 21567
BUFSIZ =1024
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data1 = input('>')
#data = str(data)
if not data1:
break
tcpCliSock.send(data1.encode())
data1 = tcpCliSock.recv(BUFSIZ)
if not data1:
break
print(data1.decode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
# tcpCliSock.send('[%s] %s' %(bytes(ctime(),'utf-8'),data))
tcpCliSock.send(('%s' % (data)).encode())
print(data.decode('utf-8'))
tcpCliSock.close()
帮我看看能不能实现两个电脑之间的局域网通讯。
两个电脑连的是同一个网络。
感谢解答
这个代码要用到socket,pip install socket
a:
import socket
Sockin = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #新建socket
Sockin.bind(('IP地址',23000)) #socket绑定该主机的ip和端口
while True: #循环中执行收发功能
text = raw_input('> ')
Sockin.sendto(text,(('IP地址',23000))) #将 'text’ 发送给对方
if text == 'q':
Scokin.close() #退出时关闭socket
break
msg,(addr,port) = Sockin.recvfrom(100) # 接受数据
if msg == 'q':
Sockin.close()
break
print msg
b:
import socket
Sockin = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Sockin.bind(('192.168.10.8',23000))
while True:
msg,(addr,port) = Sockin.recvfrom(100)
if msg == 'q':
Sockin.close()
break
else:
print msg
text = raw_input('> ')
Sockin.sendto(text,(('192.168.10.5',23000)))
if text =='q':
Sockin.close()
break
|