简易的聊天

基于TCP:

import socket

sk = socket.socket()

sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  # 有了这段代码就可重复使用端口了。

sk.bind(('127.0.0.1',9000))

sk.listen() # 可以加参数,表示同一个时间可以有n个链接等待与server端通信

while True:
    conn,addr = sk.accept()     # 接收 连接的客户端的连接
    while True:
        ret = conn.recv(1024).decode('utf-8')   # 将接受的内容解码
        if ret.upper() == 'Q':break
        print(ret)
        inp = input('>>>')
        conn.send(inp.encode('utf-8'))
        if inp.upper() == 'Q':break
    conn.close()
sk.close()
服务器
import socket

sk = socket.socket()

sk.connect(('127.0.0.1',9000))
while True:
    inp = input('>>>')

    sk.send(inp.encode('utf-8'))

    if inp.upper() == 'Q': break

    ret = sk.recv(1024).decode('utf-8')

    if ret.upper() == 'Q':break

    print(ret)

sk.close()
客户端

基于UDP:

import socket

sk = socket.socket(type=socket.SOCK_DGRAM)

sk.bind(('127.0.0.1',9000))

while True:

        msg,addr = sk.recvfrom(1024)

        print(msg.decode('utf-8'))

        inp = input('>>>')

        sk.sendto(inp.encode('utf-8'),addr)

sk.close()
服务器
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)

while True:
    inp = input('>>>')

    if inp.upper() == 'Q':break

    sk.sendto(inp.encode('utf-8'),('127.0.0.1',9000))

    msg,addr = sk.recvfrom(1024)

    print(msg.decode('utf-8'))

sk.close()
客户端

  进阶(加上客户端的名称以及上色):

import socket

lst = {'顾清秋':'\033[1;31m','顾小白':'\033[1;34m'}  # 可以根据客户端发来的姓名选择相应的颜色

sk = socket.socket(type=socket.SOCK_DGRAM)

sk.bind(('127.0.0.1',9000))

while True:

        msg,addr = sk.recvfrom(1024)

        name,mesg = msg.decode('utf-8').split(':')      # 将姓名与发送的内容分割,提取姓名

        color = lst.get(name.strip(),'')

        print('%s%s\033[0m ' % (color,msg.decode('utf-8')))

        inp = input('>>>')

        sk.sendto(inp.encode('utf-8'),addr)

sk.close()
服务器
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)

name = input('请输入你的名字:')    # 输入名字

while True:
    inp = input('>>>')

    if inp.upper() == 'Q':break

    sk.sendto(('%s:%s' % (name,inp)).encode('utf-8'),('127.0.0.1',9000)) # 将姓名和内容按格式发送过去

    msg,addr = sk.recvfrom(1024)

    print(msg.decode('utf-8'))

sk.close()
客户端

  再次进阶(由于每次信息都需要编码解码,所以化简):

from socket import *
class Mysocket(socket):
    def __init__(self,coding = 'utf-8'):
        self.coding = coding
        super().__init__(type=SOCK_DGRAM)

    def my_recv(self,num):
        msg,addr = self.recvfrom(num)
        return msg.decode(self.coding),addr

    def my_send(self,msg,addr):
        return self.sendto(msg.encode(self.coding),addr)
my_socket
from my_socket import Mysocket

sk = Mysocket()

sk.bind(('127.0.0.1',9000))

while True:

    msg,addr = sk.my_recv(1024)

    print(msg)

    inp = input('>>>')

    sk.my_send(inp,addr)

sk.close()
服务器
from my_socket import Mysocket

sk = Mysocket()

while True:

    inp = input('>>>')

    if inp.upper() == 'Q':break

    sk.my_send(inp,('127.0.0.1',9000))

    msg,addr = sk.my_recv(1024)

    if msg.upper() == 'Q':break

    print(msg)

sk.close()
客户端

  通过服务器客户端获取实时时间:

import time

import socket

sk = socket.socket(type=socket.SOCK_DGRAM)

sk.bind(('127.0.0.1',9000))
while True:
    msg,addr = sk.recvfrom(1024)

    # print(msg.decode('utf-8'))

    sk.sendto(time.strftime('%x %X').encode('utf-8'),addr)

sk.close()
服务器
import time

import socket

sk = socket.socket(type=socket.SOCK_DGRAM)

while True:

    sk.sendto(b'time:',('127.0.0.1',9000))

    msg,addr = sk.recvfrom(1024)

    print(msg.decode('utf-8'))

    time.sleep(1)

sk.close()
客户端

 

posted @ 2018-05-04 16:43  Qingqiu_Gu  阅读(151)  评论(0编辑  收藏  举报