socket半双工聊天

2017-11-27  本文已影响0人  疯帮主
  1. 服务器
$ vim srever.py
#!/usr/bin/python3

import socket
import time


def wating():
    print('   \r', end='')
    time.sleep(0.5)
    print('.  \r', end='')
    time.sleep(0.5)
    print('.. \r', end='')
    time.sleep(0.5)
    print('...\r', end='')
    time.sleep(0.5)


def server(ADDR):
    """服务器"""

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(ADDR)
    server.listen(5)
    print("[*] 服务器已开启")
    while True:

        (client, addr) = server.accept()

        print("[+] 连接来自 %s: %d" % (addr[0], addr[1]))

        while True:

            wating()
            data = client.recv(BUFSIZ)
            if not data:
                break
            elif data.decode('utf-8') == 'exit':
                print("[-] 来自 %s 的连接断开" % addr[0])
                client.close()
                break

            print("[%s]: %s" % (addr[0],data.decode('utf-8')))

            in_data = input("[me]: ")

            if not in_data:
                continue
            elif in_data == 'exit':
                client.close()
                break
            client.send(bytes(in_data, 'utf-8'))
        client.close()
    server.close()

HOST = '127.0.0.1'
PORT = 6666
BUFSIZ = 1024
ADDR = (HOST, PORT)
server(ADDR)
  1. 客户端
$ vim client.py 
#!/usr/bin/python3

import socket
import time


def wating():
    print('   \r', end='')
    time.sleep(0.5)
    print('.  \r', end='')
    time.sleep(0.5)
    print('.. \r', end='')
    time.sleep(0.5)
    print('...\r', end='')
    time.sleep(0.5)

def client(ADDR):
    """服务器"""

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    print("[*] 客户端已开启")

    client.connect(ADDR)
    print("[+] 连接到 %s: %d" % (ADDR[0], ADDR[1]))

    while True:

        in_data = input("[me]: ")
        if not in_data:
            continue
        elif in_data == 'exit':
            client.send(bytes(in_data, 'utf-8'))
            break

        client.send(bytes(in_data, 'utf-8'))
        while True:
            wating()
            data = client.recv(BUFSIZ)
            if data is not None:
                print("[%s]: %s" % (ADDR[0], data.decode('utf-8')))
                break

    client.close()

HOST = '127.0.0.1'
PORT = 6666
BUFSIZ = 1024
ADDR = (HOST, PORT)
client(ADDR)
  1. 聊天
# 终端1
$ ./server.py 
[*] 服务器已开启
[+] 连接来自 127.0.0.1: 34332
[127.0.0.1]: hello
[me]: hello
[127.0.0.1]: good bey
[me]: good bey
[-] 来自 127.0.0.1 的连接断开
# 终端2
$ ./client.py 
[*] 客户端已开启
[+] 连接到 127.0.0.1: 6666
[me]: hello
[127.0.0.1]: hello
[me]: good bey
[127.0.0.1]: good bey
[me]: exit
上一篇下一篇

猜你喜欢

热点阅读