简体   繁体   中英

Connecting two systems in python using sockets

Actually I am trying to implement bidirectional data transfer between client and server in two systems. I can send from client to server but the reverse is not possible. Is Bidirectional communication possible among different systems?

My client program:

import sys
from socket import socket, AF_INET, SOCK_DGRAM
import time

SERVER_IP   = '172.16.142.29'
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 )
mySocket.connect((SERVER_IP,PORT_NUMBER))
while True:
       mySocket.send('cool')
       time.sleep(.5)
       (msg, addr) =mySocket.recvfrom(1234)
       print(msg)
sys.exit()

My server program:

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
    mySocket.send("hai")
sys.ext()

Thanks in advance.

Client Program:

import sys
from socket import socket, AF_INET, SOCK_DGRAM
import time

SERVER_IP   = '172.16.142.29'
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 )
mySocket.connect((SERVER_IP,PORT_NUMBER))
while True:
   mySocket.send('cool')
   time.sleep(.5)
   (msg, addr) =mySocket.recvfrom(SIZE)
   print(msg)
sys.exit()

Server Program:

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
    mySocket.sendto("hai",addr)
sys.ext()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM