简体   繁体   中英

Unable to assign IP addresses to server/client in Python Socket Programming

I'm working on a socket level chat assignment that requires me to have a server that stores Usernames and IP addr&port numbers and give it out to any client that needs it to enable chat between them. New to socket programming in Python so I'm having a tough time assigning IP addresses and also pickle serializing lists to be sent from server to client,

Server side:

import pickle
import socket
udp_ip = '127.0.0.1'
udp_port = 8014
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fd.bind((udp_ip,udp_port))
x=[]

while True:
    r = fd.recvfrom(2048)
    x.append(r)
    print x
    datas=pickle.dumps(x)
    reply = r[0]
    client_address = r[1]
    #fd.sendto(bytearray(reply,"utf-8"), client_address)
    fd.sendto(datas,client_address)

Client side:

import pickle
import socket
fd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM )


fd.getsockname()
udp_ip = '127.0.0.1'
udp_port = 8014
b=[]


print "SIGN-IN"
message= raw_input("USERNAME :")
fd.sendto(message, (udp_ip, udp_port))
while(True):
    reply = fd.recvfrom(1000)
    list1=raw_input("\n").lower().strip()
    if list1=="list":
         a=pickle.loads(reply)
         b.append(a)
         print "Here is the list of IP addr and ports",a
    else:
        print("Sorry didn't get that.")

Problem 1- Need to figure out how to assign proper IP addresses to both client and server. Any other IP other than localhost returns an error, `ERRNO99 Cannot assign requested address.

Problem 2- Pickle serialization is fantastic and I'm trying to get the list x from server to client but it throws an error on the client side,

`File"client1.py", line 21, in <module>
        a=pickle.loads(reply)
      File "/usr/lib/python2.7/pickle.py", line 1387, in loads
        file = StringIO(str)
    TypeError: StringIO() argument 1 must be string or buffer, not tuple

Problem 3- I am still trying to understand how the client will be able to just retrieve the other client's ip and port info from server's list and then contact the other client directly (no server involved). Would also like to understand bytearrays(can I get rid of them completely if I use pickle serialization)

I would appreciate as much help as possible but not asking anyone here code it entirely of course, just show me the way and let me know where I'm wrong. Links to good examples would be perfect.

because,

reply = fd.recvfrom(1000)

returns tuple (address,msg)

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