我有UDP客户端:
import socket
from threading import Thread
def wait_response(s):
while True:
data, addr = s.recvfrom(1024)
if data:
data = data.decode('utf-8')
print("Received from server: " + data)
def main():
host = ''
port = 5000
server = ('-.-.-.-', 8888)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
d = Thread(target=wait_response, args=(s,))
d.setDaemon(True)
d.start()
message = raw_input("\n->")
while message != 'q':
s.sendto(message.encode('utf-8'), server)
message = raw_input("->")
s.close()
if __name__ == '__main__':
main()
我有UDP服务器:
import socket
from threading import Thread
def wait_response(s, c_a):
while True:
data, addr = s.recvfrom(1024)
if data:
c_a.addr = addr
data = data.decode('utf-8')
print("Recived from client: " + data)
class Upd_client_address_container(object):
addr = ''
def main():
host = "---.---.---.---" # my ip here
port = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
connection_addr = Upd_client_address_container()
d = Thread(target=wait_response, args=(s, connection_addr,))
d.deamon = True
d.start()
print("Server started")
message = 'Connection with server established'
while message != 'q':
if connection_addr.addr:
s.sendto(message.encode('utf-8'), connection_addr.addr)
message = raw_input("->")
s.close()
if __name__ == "__main__":
main()
我已在公司网络内测试过,它运行正常。但是当我在本地网络之外发送client
部分时,我们无法建立连接。应该采取哪些措施来解决这个问题?