欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket

程序员文章站 2022-04-24 11:41:19
...

socket用于底层通信,常用于长连接。短连接底层也是基于socket.比如Http访问。
socket一般分为客户端和服务器端2个部分。

tcp

客户端

#!/usr/bin/env python3
#_*_encoding:utf-8_*_

import socket
def socket_client():
    #1 create socket
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    #2 point host
    host = socket.gethostname()
    print(host)
    #3 point port
    port = 9999
    #4 connect
    s.connect((host,port))
    # once connected to server ,Server may send some message to client without client send request
    print(s.recv(1024).decode('utf-8'))
    #5 send message and recieve message
    for data in ['xiaomeng','xiaozhi','xiaoqiang']:
        s.send(data.encode('utf-8'))
        print(s.recv(1024).decode('utf-8'))
    s.send(b'exit')
    #7 close socket
    s.close()
    
def main():
    socket_client()
if __name__ == '__main__':
    main()

服务端

import socket

import threading
import time

def socket_server():
    server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 9999
    server_socket.bind((host,port))
    server_socket.listen(5)
    while True:
        sock,addr = server_socket.accept()
        t = threading.Thread(target=tcp_link,args=(sock,addr))
        t.start()
def tcp_link(sock,addr):
    print('accept',addr)
    sock.send('欢迎学习Python'.encode('utf-8'))
    while True:
        data = sock.recv(1024)
        #time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('hello.%s!' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('server receive connect close with',addr)
    
def main():
    socket_server()
if __name__ == '__main__':
    main()

UDP

没有TCP安全

客户端

#!/usr/bin/env python3
#_*_encoding:utf-8_*_

import socket
def socket_client():
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    host = socket.gethostname()
    port = 9999
    for i in ['aa','vv']:
        s.sendto(i.encode('utf-8'),(host,port))
        print(s.recv(1024).decode('utf-8'))
def main():
    socket_client()
if __name__ == '__main__':
    main()

服务端

import socket

import threading
import time

def socket_server():
    server_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    host = socket.gethostname()
    port = 9999
    server_socket.bind((host,port))
    while True:
        data,addr = server_socket.recvfrom(1024)
        server_socket.sendto(b'hello %s' % data,addr) 
def main():
    socket_server()
if __name__ == '__main__':
    main()

上一篇: socket

下一篇: Channels学习笔记