网络编程后续

import socket
import time
tcpsocket = socket.socket()
tcpsocket.bind(('127.0.0.1',8090))
tcpsocket.listen()
while 1:
    conn,addr = tcpsocket.accept()
    print('端口为{},链接为{}'.format(addr,conn))
    while  1:
        ret = conn.recv(1024).decode('utf-8')
        print(ret)
        timeinfo = time.strftime('%y-%m-%d %H-%M-%S',time.localtime(time.time()))
        conn.send(bytes(timeinfo,encoding='utf-8'))
客户端
import socket
tcpsock = socket.socket()
tcpsock.connect(('127.0.0.1',8090))
while 1:
    info = input('>>>>>>>>>>')
    tcpsock.send(bytes(info,encoding='utf-8'))
    ret = tcpsock.recv(1024).decode('utf-8')
    print(ret)
tcpsock.close()

udp 多方会谈

服务端
import socket
udpsock = socket.socket(type=socket.SOCK_DGRAM)
udpsock.bind(('127.0.0.1',8080))
while 1:
    ret,add = udpsock.recvfrom(1024)
    print(ret.decode('utf-8'))
    udpsock.sendto(b'111111',add)
客户端
import socket
update = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8080)
while 1:
    info = input('>>>>>>>>')
    update.sendto(bytes(info, encoding='utf-8'),ip_port)
    ret,add = update.recvfrom(1024)
    print(ret.decode('utf-8'))
客户端1
import socket
update = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8080)
while 1:
    info = input('>>>>>>>>')
    update.sendto(bytes(info, encoding='utf-8'),ip_port)
    ret,add = update.recvfrom(1024)
    print(ret.decode('utf-8'))
#tcp粘包现象
import socket
tcpsock = socket.socket()
tcpsock.bind(('127.0.0.1',8080))
tcpsock.listen()
while 1:
    conn,addr = tcpsock.accept()
    while 1:
        ret = conn.recv(1024).decode('utf-8')
        ret1 = conn.recv(1024).decode('utf-8')
        print('第一次接收为{}'.format(ret))
        print('第二次接收为{}'.format(ret1))

conn.close()
tcpsock.close()
客户端
import socket
tcpsock = socket.socket()
tcpsock.connect(('127.0.0.1',8080))
while 1:
    tcpsock.send(bytes('hollowordmuwyreiuweyriuweyruiweyruiwyeiryweuiryweuiryweiury',encoding='utf-8'))
    tcpsock.send(bytes('hoit123',encoding='utf-8'))
原文地址:https://www.cnblogs.com/Ebola-/p/8360345.html