首页 > 代码库 > python之socket

python之socket

socket

socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求。

技术分享

技术分享
import socket

sk = socket.socket()
sk.bind((127.0.0.1, 9999,))     #设置ip,post
sk.listen()                               #监听
while True:
    conn, address = sk.accept()
    conn.sendall(bytes(hello world, encoding=utf-8))
    while True:
        ret = conn.recv(1024)
        ret_str = str(ret, encoding=utf-8)
        if ret_str == "q":
            break
        else:
            conn.sendall(bytes(ret_str + "yes", encoding=utf-8))
scoket 服务端
技术分享
import socket

obj = socket.socket()
obj.connect((127.0.0.1, 9999,))
result = obj.recv(1024)
re = str(result, encoding=utf-8)
print(re)
while True:
    inp = input(请输入内容:)
    if inp == q:
        break
    else:
        obj.sendall(bytes(inp, encoding=utf-8))
        ret = str(obj.recv(1024), encoding=utf-8)
        print(ret)
obj.close()
socket 客户端
技术分享
#!/usr/bin/env python
#coding:utf-8
import socket
 
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n")
    client.send("Hello, World")
 
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((localhost,8080))
    sock.listen(5)
 
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()
 
if __name__ == __main__:
  main()
web 服务应用

 

socketserver

SocketServer内部使用 IO多路复用 以及 “多线程” 和 “多进程” ,从而实现并发处理多个客户端请求的Socket服务端。即:每个客户端请求连接到服务器时,Socket服务端都会在服务器是创建一个“线程”或者“进 程” 专门负责处理当前客户端的所有请求。

技术分享

技术分享
import socketserver

class MyServer(socketserver.BaseRequestHandler):

    def handle(self):
        conn = self.request
        conn.sendall(bytes(hello world, encoding=utf-8))
        while True:
            ret = conn.recv(1024)
            ret_str = str(ret, encoding=utf-8)
            if ret_str == "q":
                break
            else:
                conn.sendall(bytes(ret_str + "yes", encoding=utf-8))

if __name__ == __main__:
    server = socketserver.ThreadingTCPServer(("127.0.0.1", 9999), MyServer)
    server.serve_forever()
socketserver
技术分享
import socket

obj = socket.socket()
obj.connect((127.0.0.1, 9999,))
result = obj.recv(1024)
re = str(result, encoding=utf-8)
print(re)
while True:
    inp = input(请输入内容:)
    if inp == q:
        break
    else:
        obj.sendall(bytes(inp, encoding=utf-8))
        ret = str(obj.recv(1024), encoding=utf-8)
        print(ret)
obj.close()
客户端

 

IO多路复用

I/O多路复用指:通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作。

技术分享
import socket
import select

sk = socket.socket()
sk.bind(("127.0.0.1", 8001))
sk.listen()


inputs = [sk]
output = []
message_dict = {}

while True:
    r_list, w_list, e_list = select.select(inputs, output, inputs, 1)
    print("监听%d个对象" %len(inputs))

    for sk_or_conn in r_list:
        if sk_or_conn == sk:
            conn, address = sk_or_conn.accept()
            inputs.append(conn)
            message_dict[conn] = []

        else:
            try:
                data = sk_or_conn.recv(1024)

            except Exception as ex:
                print(ex)
                inputs.remove(sk_or_conn)

            else:
                data_str = str(data, encoding="utf-8")
                #sk_or_conn.sendall(bytes(data_str + "good", encoding="utf-8"))
                message_dict[sk_or_conn].append(data_str)
                output.append(sk_or_conn)

    for conn in output:
        message = message_dict[conn][0]
        del message_dict[conn][0]
        conn.sendall(bytes( message + "good", encoding="utf-8"))
        output.remove(conn)
服务器端
技术分享
import socket

conn = socket.socket()
conn.connect(("127.0.0.1", 8001))
while True:
    inputs = input(">>>>>")
    conn.sendall(bytes(inputs, encoding="utf-8"))
    ret = conn.recv(1024)
    print(str(ret, encoding="utf-8"))
客户端

 

python之socket