Python--网络编程-----socket代码实例--聊天软件升级版

服务端代码:

 1 import socket
 2 
 3 HOST = ''
 4 PORT = 50007
 5 
 6 sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 7 sock_server.bind((HOST, PORT))
 8 
 9 sock_server.listen(1)
10 
11 while True:
12     conn, addr = sock_server.accept()
13 
14     with conn:
15         print('Connected by', addr)
16         while True:
17             try:
18                 data = conn.recv(1024)
19                 print("server recv:", conn.getpeername(), data.decode())
20                 if not data:
21                     break
22 
23                 conn.send(data.upper())
24                 print("send to alex:", data)
25             except ConnectionResetError:
26                 break

客户端1代码:

import socket

HOST = 'localhost'
PORT = 50007

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

while True:
    msg = input(">>>:").strip()
    if len(msg) == 0:
        continue
    client.sendall(msg.encode())

    data = client.recv(1024)

    print('Received', data.decode())

客户端2代码:

 1 import socket
 2 
 3 HOST = 'localhost'
 4 PORT = 50007
 5 
 6 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 7 client.connect((HOST, PORT))
 8 
 9 while True:
10     msg = input(">>>:").strip()
11     if len(msg) == 0:
12         continue
13     client.sendall(msg.encode())
14 
15     data = client.recv(1024)
16 
17     print('Received', data.decode())

先开启服务端,然后开启客户端1,客户端2,在客户端1输入信息能够收到服务端的响应信息,在客户端2输入信息不能收到服务端的响应信息,此时断开客户端1 的连接,客户端2可以正常收到服务端的响应信息,

客户端1运行结果:

1 >>>:客户端1
2 Received 客户端1
3 >>>:
4 Process finished with exit code 1

客户端2运行结果:

1 >>>:客户端2
2 Received 客户端2
3 >>>:

服务端运行结果:

1 Connected by ('127.0.0.1', 58852)
2 server recv: ('127.0.0.1', 58852) 客户端1
3 send to alex: b'\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf1'
4 Connected by ('127.0.0.1', 58857)
5 server recv: ('127.0.0.1', 58857) 客户端2
6 send to alex: b'\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf2'

 

posted @ 2018-04-11 23:21  xudachen  阅读(208)  评论(0编辑  收藏  举报