Friday 14 August 2020

python sockets

#client 1 cmd

C:\Users\bob\python sockets>py client.py
my message: I am first client
192.168.0.18: I am first client

C:\Users\bob\python sockets>py client.py
my message: say hello from first client
192.168.0.18: say hello from first client
I am second client
I am first client

C:\Users\bob\python sockets>py client.py
my message: I see another client is online, he should be second
192.168.0.18: I see another client is online, he should be second
How are you from second client
say hello from first client
I am second client
I am first client

-------------------------------------
#client 2 cmd

C:\Users\zchen\python sockets>py client.py
my message: I am second client
192.168.0.24: I am second client
I am first client

C:\Users\zchen\python sockets>py client.py
my message: How are you from second client
192.168.0.24: How are you from second client
say hello from first client
I am second client
I am first client

C:\Users\zchen\python sockets>py client.py
my message: There must be a client before me, he is the first
192.168.0.24: There must be a client before me, he is the first
I see another client is online, he should be second
How are you from second client
say hello from first client
I am second client
I am first client

-----------------------------
#server

C:\Users\bob\python sockets>py server.py
Connected by 192.168.0.18
Connected by 192.168.0.24
Connected by 192.168.0.18
Connected by 192.168.0.24
Connected by 192.168.0.18
Connected by 192.168.0.24

--------------------------------
#sever.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#address + port#
s.bind((socket.gethostname(), 6666))
s.listen(5)

record = ''

while True:
    conn, adr = s.accept()
    print(f"Connected by {adr[0]}")

    with conn:
        while True:
            data = conn.recv(1024)
            if not data:
                break
            record = data.decode('utf-8') + '\n' + record
            conn.sendall(bytes(f"{adr[0]}: {record}", "utf-8"))
        #conn.close()

---------------------------------
#client.py

import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    #connect to server address
    s.connect('192.168.0.18', 6666))

    msg = input('my message: ')
    s.send(bytes(f"{msg}", "utf-8"))
    data = s.recv(1024)
    print(data.decode("utf-8"))
 
reference:

No comments:

Post a Comment