socket 第一课

基于TCP的socket服务

server.py

import socket

sk = socket.socket()
sk.bind(("127.0.0.1",8080))
sk.listen()

conn,addr = sk.accept()

while 1:

    ret = conn.recv(1024).decode('utf-8')
    if 'bye' in ret:
        conn.send(b'byebye~~')
        break
    print(ret)

    info = input('-->: ')
    conn.send(bytes(info,encoding = 'utf-8'))

conn.close()
sk.close()

client.py

import socket

sk = socket.socket()

sk.connect(("127.0.0.1",8080))

while 1:


    info = input('-->: ')
    sk.send(bytes(info,encoding = 'utf-8',))

    ret = sk.recv(1024).decode('utf-8')
    if 'bye' in ret:
        break
    print(ret)

sk.close()

基于UDP的socket服务

server.py

import socket

sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1',8080))
msg, addr = sk.recvfrom(1024)

print(msg.decode('utf-8'))
sk.sendto(b'byebye~client', addr)

sk.close()

client.py

import socket

sk = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8080)

sk.sendto(b'hello server', ip_port)
ret, addr = sk.recvfrom(1024)
print(ret.decode('utf-8'))

sk.close()

udp的server 不需要进行监听,也不需要建立连接

在启动服务之后只能被动的等待client发送消息

client发送消息的同时还会自带地址信息

消息回复的时候不仅需要发送消息,还要把自己的地址发送过去

tcp相反

原文地址:https://www.cnblogs.com/Hxx0916/p/9713501.html