python连接两台电脑_使用python套接字的两台计算机之间的通信

I am using these two programs to communicate between two of my computers, one that I am ssh'd into and I am not returning anything on either side. It just runs without sending anything

client

import sys

from socket import socket, AF_INET, SOCK_DGRAM

SERVER_IP = '127.0.0.1'

PORT_NUMBER = 5000

SIZE = 1024

print ("Test client sending packets to IP {0}, via port {1}\n".format(SERVER_IP, PORT_NUMBER))

mySocket = socket( AF_INET, SOCK_DGRAM )

while True:

mySocket.sendto('cool',(SERVER_IP,PORT_NUMBER))

sys.exit()

server

from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM

import sys

PORT_NUMBER = 5000

SIZE = 1024

hostName = gethostbyname( '0.0.0.0' )

mySocket = socket( AF_INET, SOCK_DGRAM )

mySocket.bind( (hostName, PORT_NUMBER) )

print ("Test server listening on port {0}\n".format(PORT_NUMBER))

while True:

(data,addr) = mySocket.recvfrom(SIZE)

print data

sys.ext()

What could I be doing wrong?

解决方案

The problem is in the address of your client:

SERVER_IP = '127.0.0.1'

You are connecting to the local machine and sending data, while your server is sitting on a different ip. You need to connect to either the servers ip or hostname.

You can verify this by making the client connect first (and fail if it cant)

...

import time

mySocket = socket( AF_INET, SOCK_DGRAM )

mySocket.connect((SERVER_IP,PORT_NUMBER))

while True:

mySocket.send('cool')

time.sleep(.5)

Update from comments

Because you are on a wifi connection, that implies that both these machine are on the local network. You need to find the LAN ip address of the server, to specify it as the target.

Command-line approach to finding your IP

OSX/Linux: ifconfig

Windows: ipconfig /all

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值