1.Socket实例
Server端:
import socket
server = socket.socket() #生成socket实例
server.bind(('localhost',9999)) #绑定ip port
server.listen() #开始监听
conn,addr = server.accept() #接受并建立与客户端的连接,程序开始阻塞,直到有客户端连接进来
print("新连接:",addr)
data = conn.recv(1024)
print("收到消息:",data)
server.close()
Client端:
import socket
client = socket.socket()
client.connect(('localhost',9999))
clinet.send(b"Hello World ") #注意:在py3中socket只能发送bytes类型的数据
client.close()
2.可多次交互得的Socket实例
Server端:
import socket
server = socket.socket() #获得socket实例
server.bind(("localhost",9999)) #绑定ip port
server.listen() #开始监听
print("等待客户端的连接...")
conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:",addr )
while True:
data = conn.recv(1024)
if not data: #这里解决客户端断开,服务器陷入死循环的问题
print("客户端断开。。。。")
break
print("收到消息:",data)
conn.send(data.upper())
server.close()
Client端:
import socket
client = socket.socket()
client.connect(('localhost',9999))
while True:
msg = input(">>:").strip()
if len(msg) == 0: continue
client.send((msg.encode("utf-8"))
data = client.recv(1024)
print("来自服务器:",data)
client.close()
3.Socket实现多连接处理
上面的代码实现了服务端和客户端的交互,但是有个问题,一旦客户端断开连接,服务端也会断开,这就有点尴尬了,可以通过在加入一层循环的方式解决。下面解决这个问题
import socket
server = socket.socket() #获得socket实例
server.bind(("localhost",9998)) #绑定ip port
server.listen() #开始监听
while True: #第一层loop
print("等待客户端的连接...")
conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:",addr )
while True:
data = conn.recv(1024)
if not data:
print("客户端断开了...")
break #这里断开就会再次回到第一次外层的loop
print("收到消息:",data)
conn.send(data.upper())
server.close()
但是这时,服务端依然只能服务一个client,其他连接进来需要排队等待。。。【这个可以在后面使用多线程的方式来实现同时处理多个用户的交互】
4.使用Socket实现简单的ssh
Server端:
#_*_coding:utf-8_*_
__author__ = 'Chen'
import socket
import os,subprocess
server = socket.socket() #获得socket实例
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("localhost",9999)) #绑定ip port
server.listen() #开始监听
while True: #第一层loop
print("等待客户端的连接...")
conn,addr = server.accept() #接受并建立与客户端的连接,程序在此处开始阻塞,只到有客户端连接进来...
print("新连接:",addr )
while True:
data = conn.recv(1024)
if not data:
print("客户端断开了...")
break #这里断开就会再次回到第一次外层的loop
print("收到命令:",data)
#res = os.popen(data.decode()).read() #py3 里socket发送的只有bytes,os.popen又只能接受str,所以要decode一下
res = subprocess.Popen(data,shell=True,stdout=subprocess.PIPE).stdout.read() #跟上面那条命令的效果是一样的
if len(res) == 0:
res = "cmd exec success,has not output!".encode("utf-8")
conn.send(str(len(res)).encode("utf-8")) #发送数据之前,先告诉客户端要发多少数据给它
print("等待客户ack应答...")
client_final_ack = conn.recv(1024) #等待客户端响应
print("客户应答:",client_final_ack.decode())
print(type(res))
conn.sendall(res) #发送端也有最大数据量限制,所以这里用sendall,相当于重复循环调用conn.send,直至数据发送完毕
server.close()
Client端:
#coding:utf-8
author = 'Alex Li'
import socket
import sys
client = socket.socket()
client.connect(("localhost",9999))
while True:
msg = input(">>:").strip()
if len(msg) == 0:continue
client.send( msg.encode("utf-8") )
res_return_size = client.recv(1024) #接收这条命令执行结果的大小
print("getting cmd result , ", res_return_size)
total_rece_size = int(res_return_size)
print("total size:",res_return_size)
client.send("准备好接收了,发吧loser".encode("utf-8"))
received_size = 0 #已接收到的数据
cmd_res = b''
f = open("test_copy.html","wb")#把接收到的结果存下来,一会看看收到的数据 对不对
while received_size != total_rece_size: #代表还没收完
data = client.recv(1024)
received_size += len(data) #为什么不是直接1024,还判断len干嘛,注意,实际收到的data有可能比1024少
cmd_res += data
else:
print("数据收完了",received_size)
#print(cmd_res.decode())
f.write(cmd_res) #把接收到的结果存下来,一会看看收到的数据 对不对
#print(data.decode()) #命令执行结果
client.close()
接收大数据客户端
5.Socket—Server模块
Server端:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Client端:
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
finally:
sock.close()
print("Sent: {}".format(data))
print("Received: {}".format(received))