TCP
import socket
# 1.创建一个socket,AF_INET代表IPv4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 2.建立连接,前者是域名或者IP,后者是端口号,Web是80,FTP是21,127.0.0.1是表示本机地址
s.connect(('127.0.0.1',9999))
# 3接受消息,每次最多接受1k字节
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael', b'Tracy', b'Sarah']:
#4发送消息
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()
import socket, threading, time
#1.创建socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#2.监听端口,listen参数代表传入的参数指定等待连接的最大数量
s.bind(('127.0.0.1', 9999))
s.listen(5)
print('waiting for connection')
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send(b'Welcome')
while True:
data = sock.recv(1024)
time.sleep(1)
#如果客户端发送exit字符串,就关闭连接
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
sock.close()
print('connection from %s:%s closed' % addr)
while True:
#3.接受一个新连接
sock, addr = s.accept()
#4.创建新线程来处理TCP连接
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
UDP
import socket
# 1.创建一个socket,AF_INET代表IPv4
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Michael', b'Tracy', b'Sarah']:
#4发送消息
s.sendto(data,('127.0.0.1', 9999))
print(s.recv(1024).decode('utf-8'))
s.close()
import socket, threading, time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('127.0.0.1', 9999))
print('waiting for connection')
while True:
data, addr = s.recvfrom(1024)
print('Received from %s:%s' % addr)
s.sendto(b'hello,%s' % data, addr )