网络编程

一. tcp

1.tcp 的socket

服务端

# 服务端
import socket
sk = socket.socket()
sk.bind(('127.0.0.1', 8080))
sk.listen()
conn, addr = sk.accept()
ret = conn.recv(1024)
print(ret)
conn.send(b'hello')
conn.close()
sk.close()

客户端

# 客户端
import socket
sk = socket.socket()
sk.connect(('127.0.0.1', 8080))
sk.send(b'hi')
ret = sk.recv(1024)
print(ret)
sk.close()

二 udp

服务端

import socket
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#  ipv4, udp的报文
sk.bind(('127.0.0.1', 8080))
ret, addr = sk.recvfrom(1024)
print(ret.decode('utf-8'))
sk.sendto(b'ok', addr)
sk.close()

客户端

import socket
sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_port = ('127.0.0.1', 8080)
sk.sendto(b'are you ok', ip_port)
ret, addr = sk.recvfrom(1024)
print(ret)
sk.close()

 

你可能感兴趣的:(python)