服务器端编程步骤
1.创建socket对象
2.绑定IP地址和端口 bind()方法
3.开始监听,将在指定的IP的端口上监听 listen()方法
4.获取用于传送数据的socker对象 socket.accept()
接收数据 recv(bufsize)
发送数据 sedn(bytes)
-----------------------------------------------
import socket
import time
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
#TCP sever
sock =socket.socket() #1 创建socket对象
ip ='127.0.0.1'
port =8000
addr =(ip,port)
sock.bind(addr) #2 IP PORT 绑定
sock.listen() #3 PORT监听
conn,clientinfo =sock.accept() #建立连接 阻塞在中
logging.info(conn)
logging.info(clientinfo)
data =conn.recv(1024) #接收数据
logging.info(data.decode())
msg = "kanghaibin"
conn.send(msg.encode()) #发送数据
conn.close()
sock.close() #关闭连接
---------------------------------------------------
import threading
import socket
import time
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
#TCP sever
sock =socket.socket() #1 创建socket对象
ip ='127.0.0.1'
port =8000
addr =(ip,port)
sock.bind(addr) #2 IP PORT 绑定
sock.listen() #3 启动监听
conn,clientinfo =sock.accept() #建立连接 阻塞在中 等待连接
logging.info(conn)
logging.info(clientinfo)
while True:
data =conn.recv(1024) #接收数据
if data.decode() == "quit":
logging.info("connection dropped!")
break
else:
logging.info(data.decode())
msg = "ack -->{} is OK".format(data.decode())
conn.send(msg.encode()) # 发送数据
conn.close()
sock.close() #关闭连接
----------------------------------------------------------
import threading
import socket
import time
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class ChatServer:
def __init__(self,ip='127.0.0.1',port=8888):
self.socke =socket.socket()
self.addr =(ip,port)
def start(self):
self.socke.bind(self.addr)
self.socke.listen()
threading.Thread(target=self._accept,name="thread_accept").start()
def stop(self):
self.socke.close()
def _accept(self):
conn,clientinfo =self.socke.accept()
logging.info(conn)
logging.info(clientinfo)
threading.Thread(target=self._recv,args=(conn,),name="recv_work").start()
def _recv(self,connet):
while True:
data =connet.recv(1024) #接收数据
if data.decode() == "quit":
logging.info("connection dropped!")
break
else:
logging.info(data.decode())
cs =ChatServer()
cs.start()
----------------------------------------------------------------------------------
import threading
import socket
import time
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class ChatServer:
def __init__(self,ip='127.0.0.1',port=8888):
self.socke =socket.socket()
self.addr =(ip,port)
self.client ={}
def start(self):
self.socke.bind(self.addr)
self.socke.listen()
threading.Thread(target=self._accept,name="thread_accept").start()
def stop(self):
for cn in self.client.values():
cn.close()
self.socke.close()
def _accept(self):
while True:
conn,clientinfo =self.socke.accept()
self.client[clientinfo] =conn
logging.info(conn)
logging.info(clientinfo)
threading.Thread(target=self._recv,args=(conn,),name="recv_work").start()
def _recv(self,conn):
while True:
data =conn.recv(1024) #接收数据
if data.decode() == "quit":
self.stop()
logging.info("connection dropped!")
break
else:
logging.info(data.decode())
msg ="ack -->{}".format(data.decode)
for conn in self.client.values():
conn.send(msg.encode())
cs =ChatServer()
cs.start()
def ShowThread():
while not threading.Event().wait(5):
logging.info(threading.enumerate())
ShowThread()
-------------------------------------------------------------
import threading
import socket
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class ChatServer:
def __init__(self,ip='127.0.0.1',port=8888):
self.socke =socket.socket()
self.addr =(ip,port)
self.client ={}
self.event =threading.Event()
def start(self):
self.socke.bind(self.addr)
self.socke.listen()
threading.Thread(target=self._accept,name="thread_accept").start()
def stop(self):
for cn in self.client.values():
cn.close()
self.socke.close()
def _accept(self):
while not self.event.is_set():
conn,clientinfo =self.socke.accept()
self.client[clientinfo] =conn
logging.info(conn)
logging.info(clientinfo)
threading.Thread(target=self._recv,args=(conn,),name="recv_work").start()
def _recv(self,conn):
while not self.event.is_set():
data =conn.recv(1024) #接收数据
if data.decode() == "quit":
self.stop()
logging.info("connection dropped!")
break
else:
logging.info(data.decode())
msg ="ack -->{}".format(data.decode)
for conn in self.client.values():
conn.send(msg.encode())
cs =ChatServer()
cs.start()
def ShowThread():
while not threading.Event().wait(5):
logging.info(threading.enumerate())
ShowThread()
--------------------------------------------------------------
import threading
import socket
import logging
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class ChatServer:
def __init__(self,ip='127.0.0.1',port=8888):
self.socke =socket.socket()
self.addr =(ip,port)
self.client ={}
self.event =threading.Event()
def start(self):
self.socke.bind(self.addr)
self.socke.listen()
threading.Thread(target=self._accept,name="thread_accept").start()
def stop(self):
for cn in self.client.values():
cn.close()
self.event.set()
self.socke.close()
def _accept(self):
while not self.event.is_set():
conn,clientinfo =self.socke.accept()
self.client[clientinfo] =conn
logging.info(conn)
logging.info(clientinfo)
logging.info(type(clientinfo))
threading.Thread(target=self._recv,args=(conn,clientinfo),name="recv_work").start()
def _recv(self,conn,clientinfo=None):
while not self.event.is_set():
try:
data =conn.recv(1024) #接收数据
except Exception as e:
logging.info(e)
data = b"quit"
data =data.decode()
logging.info(data)
if data == "quit":
self.client.pop(clientinfo)
conn.close()
logging.info("revc------>quit")
break
msg = "ack -->{}".format(data)
for conn in self.client.values():
conn.send(msg.encode())
cs =ChatServer()
cs.start()
def ShowThread():
while not threading.Event().wait(5):
logging.info(threading.enumerate())
threading.Thread(target=ShowThread,daemon=True,name="thread_showthread").start()
while True:
cmd = input(">>>").strip()
if cmd == "quit":
cs.stop()
break
----------------------------------------------------------------------------------
1.通=过BaseRequesHandler类进行子类化并覆盖handle()方法来创建请求处理程序类
import logging
import threading
import socketserver
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class MyHandler(socketserver.BaseRequestHandler):
def setup(self):
super().setup()
self.event =threading.Event()
def handle(self):
logging.info('{},{},{}'.format(self.server,self.request,self.client_address))
super(MyHandler, self).handle()
while not self.event.is_set():
data =self.request.recv(1024) #接收阻塞
msg ="your msg ack --->{}".format(data.decode()).encode()
logging.info(msg)
def finish(self):
super(MyHandler, self).finish()
self.event.set()
#启动服务
addr =('127.0.0.1',8800)
serv =socketserver.ThreadingTCPServer(addr,MyHandler)
serv.serve_forever()
serv.server_close()
------------------------------------------------------------------------------------
import logging
import threading
import socketserver
import tools
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO,format=FORMAT)
class HardlerServer(socketserver.BaseRequestHandler):
clients ={}
def setup(self):
super(HardlerServer, self).setup()
self.event=threading.Event()
def handle(self):
super(HardlerServer, self).handle()
conn =self.request
while not self.event.is_set():
try:
data =conn.recv(1024) # 接收数据
except Exception as e:
logging.info(e)
data = b"quit"
data = data.decode().strip()
logging.info(data)
if data == "quit":
break
self.clients[self.client_address] =conn
msg ="ack -->{}".format(data)
for c in self.clients.values():
c.send(msg.encode())
def finish(self):
self.event.set()
self.clients.pop(self.client_address)
super(HardlerServer, self).finish()
IP = '127.0.0.1'
PORT =8800
addr =(IP,PORT)
server =socketserver.ThreadingTCPServer(addr,HardlerServer)
threading.Thread(target=server.serve_forever,name="myserver_thread").start()
tools.Show_Threads()
while True:
cmd =input(">>>").strip()
print(cmd)
if cmd == "quit":
server.shutdown()
server.server_close()
break