python自学python基础库使用

python编写简单聊天程序

2018-10-13  本文已影响2人  渔父歌

socket模块相关的方法和类

简单的 socket服务器端

import socket


HOST = '127.0.0.1'
PORT = 8888

server = socket.socket()
server.bind((HOST, PORT))
server.listen(1)


print(f'the server is listening at {HOST}:{PORT}')
print('waiting for conntection...')
conn, addr = server.accept()

print(f'connect success addr={addr}')
print('waiting for message')
while True:
    msg = conn.recv(1024)
    print('the clint send:', msg.decode())
    response = input('enter your response: ')
    conn.send(response.encode())
    print('waiting for answer')
    

简单的 socket客户端

import socket
import sys


try:
    host, port = input('please enter host address like host:port: ').split(':')
except ValueError:
    print('the address is wrong')
    sys.exit(-1)

if len(host) == 0 or len(port) == 0:
    print('the address is wrong')
    sys.exit(-1)
else:
    client = socket.create_connection((host, int(port)))
    
    print('connect successfully. waiting for response...')
    
    client.send(b'hello server.')
    while True:
        response = client.recv(1024)
        print('the response is:', response.decode())
        msg = input('please enter a answer: ')
        client.send(msg.encode())
        print('waiting for response...')

运行截图:

上一篇下一篇

猜你喜欢

热点阅读