# coding: utf-8import socket
import threading
import time
defdealClient(sock, addr):# 第四步:接收传来的数据,并发送给对方数据print("Accept new connection from {0[0]}: {0[1]} ...".format(addr))
sock.send(b"Hello, I am server")whileTrue:
data = sock.recv(1024)
time.sleep(1)if(not data)or data.decode("utf-8")=="exit":breakprint("-->> {}!".format(data.decode("utf-8")))
sock.send(("Loop_Msg: {}!".format(data.decode("utf-8"))).encode("utf-8"))# 第五步:关闭Socket
sock.close()print("Connection from {0[0]}: {0[1]} closed.".format(addr))if __name__ =="__main__":# 第一步:创建一个基于IPv4和TCP协议的Socket# Socket绑定的IP(127.0.0.1为本机IP)与端口
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost",9999))# 第二步:监听连接
s.listen(5)print("Waiting for connection ...")whileTrue:# 第三步:接收一个新连接:
sock, addr = s.accept()# 创建新线程来处理TCP连接:
t = threading.Thread(target=dealClient, kwargs={"sock": sock,"addr": addr})
t.start()
Waiting for connection ...
Exception in thread Thread-6:
Traceback (most recent call last):
File "D:\ProgramData\Anaconda3\envs\crawler\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "D:\ProgramData\Anaconda3\envs\crawler\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-1-1f58b9482d03>", line 8, in dealClient
print("Accept new connection from {}: {} ...".format(addr))
IndexError: tuple index out of range
TCP客户端
创建Socket,连接远程地址。
连接后发送数据和接收数据。
传输完毕后,关闭Socket。
# coding: utf-8import socket
# 初始化Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 连接目标的IP和端口
s.connect(("127.0.0.1",9999))# 接收消息print("-->> {}".format(s.recv(1024).decode("utf-8")))# 发送消息
s.send(b"Hello, I am a client")print("-->> {}".format(s.recv(1024).decode("utf-8")))
s.send(b"exit")# 关闭Socket
s.close()
1.5.2 UDP编程
UDP服务器端
创建Socket,绑定指定的IP与端口。
直接发送数据和接收数据
关闭Socket。
# coding: utf-8import socket
# 创建Socket,绑定指定IP和端口# SOCK_DGRAM指定了这个Socket的类型是UDP,绑定端口与TCP示例一样
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("127.0.0.1",9999))print("Bind UDP on 9999 ...")whileTrue:# 直接发送数据和接收数据
data, addr = s.recvfrom(1024)print("Received from {0[0]}: {0[1]}".format(addr))
s.sendto(("Hello, {}".format(data.decode("utf-8"))).encode("utf-8"), addr)
Bind UDP on 9999 ...
Received from 127.0.0.1: 52155
Received from 127.0.0.1: 52155
UDP客户端
创建Socket
直接发送数据和接收数据
关闭Socket。
# coding: utf-8import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)for data in[b"Hello", b"World"]:# 发送数据
s.sendto(data,("127.0.0.1",9999))# 接收数据print(s.recv(1024).decode("utf-8"))
s.close()