Hướng dẫn how to keep a socket connection open python - cách giữ kết nối ổ cắm mở python

Đối với một vấn đề tương tự ở đây Lỗi: [errno 10053]

Tôi cũng đã thử điều tương tự và có lỗi tương tự.

Nếu có một mã đơn giản như thế này để chứng minh lỗi này:

import socket 

host = 'localhost' 
port = 5001 
size = 102400
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((host,port))
for msg in ['Hello, world','Test','anything goes here']:
    s.send(msg)
    data = s.recv(size)
    print 'Received:', data 
s.close()  

Nếu bạn tạo một đối tượng ổ cắm và AMT, nó có thể gửi và lặp lại từ máy chủ để xem máy thu của nó, nếu bạn thay đổi điều đó, hãy nói 1024 đến 102400 (trong mã này); Điều đó có nghĩa là ổ cắm không được đóng nhưng một lần nữa trong hệ điều hành Windows của tôi, phía máy chủ tiếp tục nghe và in bất kỳ dữ liệu nào mà máy khách gửi nhưng ở phía máy khách, bạn gặp lỗi này;

Tuy nhiên, nếu khách hàng chỉ có thể kết nối một lần và chỉ gửi và chỉ nhận một lần, thì đó là cách nó được thiết kế. Thử này hoạt động mà không có bất kỳ lỗi nào:

for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data

Tôi không chắc chắn nếu một đối tượng ổ cắm chỉ hoạt động một lần để gửi và nhận dữ liệu.

Cập nhật Tôi nghĩ rằng vấn đề là công suất trên mỗi ổ cắm của khách hàng để nhận dữ liệu theo bộ đệm cố định; Đó là lý do tại sao đoạn mã thứ hai ở trên hoạt động do đó tạo ra các ổ cắm kết nối máy khách mới trên máy chủ. Nhưng theo cách đó, rất nhiều ổ cắm sẽ được sử dụng hết. I think the issue was the capacity per client socket to receive data as per the buffersize fixed; That's why the second code snippet above works thus creating new client connection sockets on the server. But that way lots of sockets are going to get used up.

Thay vào đó, mã sau đã khắc phục vấn đề đó bằng cách kiểm tra AMT của kích thước được sử dụng hết. Nếu nó vượt quá số tiền đã cho, nó sẽ tạo một ổ cắm mới tại máy khách 'nhưng đảm bảo tin nhắn được gửi; Trên thực tế, vấn đề là với mã máy chủ nhưng đã sửa nó.

Kích thước = 10

Đây là một nỗ lực nhanh chóng của em bé trong mã. Tôi chắc chắn bạn sẽ hiểu và tối ưu hóa nó tốt hơn!

Mã khách hàng:

messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)

Mã máy chủ:

size = 1024  #This has to be bigger than client buf size!
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port)) 
s.listen(backlog)
while True:
        #this is what accepts and creates a P2P dedicated client socket per socket
        client, address = s.accept()
        try: 
            data = client.recv(size)
            while data or 0:
                print "Client sent {} | Server sending data to client address {}".format(data, address)
                client.send(data)
                data = client.recv(size)
            else: client.close()
        except (socket.error), e: 
            client.close()
            print e.args, e.message

Thử nó ra. Điều này sử dụng cùng một ổ cắm.

Xin chào mọi người, tôi là người mới đến Python, nhưng đã tạo thành công một thiết lập máy khách và máy chủ đơn giản, tôi có một vấn đề.
I am newbie to Python, but have successfully created a simple client and
server setup, I have one issue though.

Tôi đang cố gắng kiểm tra một hộp bằng cách gửi nhiều TCP Conns (trong khi vòng lặp) nhưng không đóng chúng bằng FIN/RST. Tuy nhiên, bất kể tôi làm gì, tôi không thể khiến vòng lặp ngừng gửi vây từ khách hàng.
closing them with a FIN/RST. However, no matter what i do, i cannot get the
loop to stop sending FIN from the client.

Bất kì manh mối nào?

Đây là kịch bản hiện tại của tôi

#!/usr/bin/python

Nhập ổ cắm, SYS từ nhập khẩu Numpy * num1 = 0
from numpy import *
num1=0

trong khi (num1

s = socket.socket (socket.af_inet, socket.sock_stream) s.settimeout (10.0) s.connect (("10.1.1.69", 50008)) # smtp in s.recv (1024) + '\ n', num1 = num1+1 #s.close () sys.exit (1)
s.settimeout(10.0)
s.connect(("10.1.1.69", 50008)) # SMTP
print s.recv(1024) + '\n',
num1=num1+1
#s.close()
sys.exit(1)

27 tháng 6 '08 #1

Một ổ cắm mạng là một điểm cuối của giao tiếp giữa các quá trình trên mạng máy tính. Thư viện tiêu chuẩn Python có một mô-đun gọi là socket cung cấp giao diện mạng Internet cấp thấp. Giao diện này là phổ biến trên các ngôn ngữ lập trình khác nhau vì nó sử dụng các cuộc gọi hệ thống cấp độ OS.

Để tạo một ổ cắm, có một hàm gọi là socket. Nó chấp nhận các đối số

for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
1,
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
2 và
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
3 (xem tài liệu để biết chi tiết). Để tạo một ổ cắm TCP, bạn nên sử dụng
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
4 hoặc
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
5 cho
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
1 và
for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
7 cho ________ 18ere Một ví dụ về ổ cắm Python:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Nó trả về một đối tượng ổ cắm có các phương thức chính sau:

  • for msg in ['Hello, world','Test','anything goes here']:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
        s.connect((host,port))
        s.send(msg)
        data = s.recv(size)
        s.close()
        print 'Received:', data
    
    9
  • messag = ['Hello, world', 'Test', 'anything goes here']
    
    def client_to_server(messag,host,port,size):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        countmsg = 0
        restmsg = ''
        for msg in messag:
            strl = tmsg = msg
            if len(restmsg):
                tmsg = restmsg + ' ' + msg
            countmsg = len(tmsg)
            if countmsg <= size:
                pass
            else:
                restmsg = tmsg[size:]
                tmsg = tmsg[:size]
                #s.close()
                countmsg = len(tmsg)
                #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                #s.connect((host, port))
            print 'Sending to server msg {}'.format(tmsg)
            s.send(tmsg)
            # s.settimeout(1)
            try: 
                data = s.recv(size)
                print 'Received:', data
                if strl == data:
                    print strl,data
                    countmsg = 0
                    restmsg = ''
            except (socket.error), e: 
                print e.args,e.message
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                s.connect((host, port))
        s.close()
        if restmsg: 
            client_to_server([restmsg],host,port,size)
        return
    
    
    client_to_server(messag,host,port,size)
    
    0
  • messag = ['Hello, world', 'Test', 'anything goes here']
    
    def client_to_server(messag,host,port,size):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        countmsg = 0
        restmsg = ''
        for msg in messag:
            strl = tmsg = msg
            if len(restmsg):
                tmsg = restmsg + ' ' + msg
            countmsg = len(tmsg)
            if countmsg <= size:
                pass
            else:
                restmsg = tmsg[size:]
                tmsg = tmsg[:size]
                #s.close()
                countmsg = len(tmsg)
                #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                #s.connect((host, port))
            print 'Sending to server msg {}'.format(tmsg)
            s.send(tmsg)
            # s.settimeout(1)
            try: 
                data = s.recv(size)
                print 'Received:', data
                if strl == data:
                    print strl,data
                    countmsg = 0
                    restmsg = ''
            except (socket.error), e: 
                print e.args,e.message
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                s.connect((host, port))
        s.close()
        if restmsg: 
            client_to_server([restmsg],host,port,size)
        return
    
    
    client_to_server(messag,host,port,size)
    
    1
  • messag = ['Hello, world', 'Test', 'anything goes here']
    
    def client_to_server(messag,host,port,size):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        countmsg = 0
        restmsg = ''
        for msg in messag:
            strl = tmsg = msg
            if len(restmsg):
                tmsg = restmsg + ' ' + msg
            countmsg = len(tmsg)
            if countmsg <= size:
                pass
            else:
                restmsg = tmsg[size:]
                tmsg = tmsg[:size]
                #s.close()
                countmsg = len(tmsg)
                #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                #s.connect((host, port))
            print 'Sending to server msg {}'.format(tmsg)
            s.send(tmsg)
            # s.settimeout(1)
            try: 
                data = s.recv(size)
                print 'Received:', data
                if strl == data:
                    print strl,data
                    countmsg = 0
                    restmsg = ''
            except (socket.error), e: 
                print e.args,e.message
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                s.connect((host, port))
        s.close()
        if restmsg: 
            client_to_server([restmsg],host,port,size)
        return
    
    
    client_to_server(messag,host,port,size)
    
    2
  • messag = ['Hello, world', 'Test', 'anything goes here']
    
    def client_to_server(messag,host,port,size):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        countmsg = 0
        restmsg = ''
        for msg in messag:
            strl = tmsg = msg
            if len(restmsg):
                tmsg = restmsg + ' ' + msg
            countmsg = len(tmsg)
            if countmsg <= size:
                pass
            else:
                restmsg = tmsg[size:]
                tmsg = tmsg[:size]
                #s.close()
                countmsg = len(tmsg)
                #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                #s.connect((host, port))
            print 'Sending to server msg {}'.format(tmsg)
            s.send(tmsg)
            # s.settimeout(1)
            try: 
                data = s.recv(size)
                print 'Received:', data
                if strl == data:
                    print strl,data
                    countmsg = 0
                    restmsg = ''
            except (socket.error), e: 
                print e.args,e.message
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                s.connect((host, port))
        s.close()
        if restmsg: 
            client_to_server([restmsg],host,port,size)
        return
    
    
    client_to_server(messag,host,port,size)
    
    3
  • messag = ['Hello, world', 'Test', 'anything goes here']
    
    def client_to_server(messag,host,port,size):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        countmsg = 0
        restmsg = ''
        for msg in messag:
            strl = tmsg = msg
            if len(restmsg):
                tmsg = restmsg + ' ' + msg
            countmsg = len(tmsg)
            if countmsg <= size:
                pass
            else:
                restmsg = tmsg[size:]
                tmsg = tmsg[:size]
                #s.close()
                countmsg = len(tmsg)
                #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                #s.connect((host, port))
            print 'Sending to server msg {}'.format(tmsg)
            s.send(tmsg)
            # s.settimeout(1)
            try: 
                data = s.recv(size)
                print 'Received:', data
                if strl == data:
                    print strl,data
                    countmsg = 0
                    restmsg = ''
            except (socket.error), e: 
                print e.args,e.message
                s.close()
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
                s.connect((host, port))
        s.close()
        if restmsg: 
            client_to_server([restmsg],host,port,size)
        return
    
    
    client_to_server(messag,host,port,size)
    
    4

for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
9,
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
0 và
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
1 là cụ thể cho ổ cắm máy chủ.
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
2 là cụ thể cho ổ cắm của khách hàng.
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
3 và
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
4 là phổ biến cho cả hai loại. Dưới đây là một ví dụ về Echo Server từ tài liệu:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 50000))
s.listen(1)
conn, addr = s.accept()
while 1:
    data = conn.recv(1024)
    if not data:
        break
    conn.sendall(data)
conn.close()

Ở đây chúng tôi tạo một ổ cắm máy chủ, liên kết nó với cổng localhost và 50000 và bắt đầu nghe các kết nối đến. Để chấp nhận kết nối đến, chúng tôi gọi phương thức

messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
1 sẽ chặn cho đến khi máy khách mới kết nối. Khi điều này xảy ra, nó tạo ra một ổ cắm mới và trả về cùng với địa chỉ của khách hàng. Sau đó, trong một chu kỳ vô hạn, nó đọc dữ liệu từ ổ cắm theo lô 1024 byte bằng phương pháp
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
4 cho đến khi nó trả về một chuỗi trống. Sau đó, nó gửi lại tất cả dữ liệu đến bằng phương pháp thuận tiện
size = 1024  #This has to be bigger than client buf size!
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port)) 
s.listen(backlog)
while True:
        #this is what accepts and creates a P2P dedicated client socket per socket
        client, address = s.accept()
        try: 
            data = client.recv(size)
            while data or 0:
                print "Client sent {} | Server sending data to client address {}".format(data, address)
                client.send(data)
                data = client.recv(size)
            else: client.close()
        except (socket.error), e: 
            client.close()
            print e.args, e.message
3 mà bên trong gọi liên tục
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
3. Và sau đó, nó chỉ đơn giản là đóng kết nối của khách hàng. Ví dụ này chỉ có thể phục vụ một kết nối đến vì nó không gọi
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
1 trong một chu kỳ.

Một mã phía máy khách trông đơn giản hơn:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50000))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Tại đây thay vì

for msg in ['Hello, world','Test','anything goes here']:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.connect((host,port))
    s.send(msg)
    data = s.recv(size)
    s.close()
    print 'Received:', data
9 và
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
0, nó chỉ gọi
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
2 và ngay lập tức gửi dữ liệu đến máy chủ. Sau đó, nó nhận được 1024 byte trở lại, đóng ổ cắm và in dữ liệu nhận được.

Tất cả các phương pháp ổ cắm đang chặn. Ví dụ: khi nó đọc từ ổ cắm hoặc ghi vào nó, chương trình không thể làm gì khác. Một giải pháp khả thi là ủy thác làm việc với khách hàng để tách các chủ đề. Tuy nhiên, việc tạo chủ đề và bối cảnh chuyển đổi giữa chúng không thực sự là một hoạt động rẻ tiền. Để giải quyết vấn đề này, có một cách làm việc không đồng bộ với ổ cắm. Ý tưởng chính là ủy thác duy trì trạng thái của ổ cắm cho hệ điều hành và để nó thông báo cho chương trình khi có một cái gì đó để đọc từ ổ cắm hoặc khi nó sẵn sàng để viết.

Có một loạt các giao diện cho các hệ điều hành khác nhau:

  • Thăm dò ý kiến, Epoll (Linux)
  • Kqueue, Kevent (BSD)
  • Chọn (Crossplatform)

Tất cả đều giống nhau, vì vậy, hãy để tạo ra một máy chủ bằng Python Chọn. Ở đây, một ví dụ Python

size = 1024  #This has to be bigger than client buf size!
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port)) 
s.listen(backlog)
while True:
        #this is what accepts and creates a P2P dedicated client socket per socket
        client, address = s.accept()
        try: 
            data = client.recv(size)
            while data or 0:
                print "Client sent {} | Server sending data to client address {}".format(data, address)
                client.send(data)
                data = client.recv(size)
            else: client.close()
        except (socket.error), e: 
            client.close()
            print e.args, e.message
9:

import select, socket, sys, Queue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server.bind(('localhost', 50000))
server.listen(5)
inputs = [server]
outputs = []
message_queues = {}

while inputs:
    readable, writable, exceptional = select.select(
        inputs, outputs, inputs)
    for s in readable:
        if s is server:
            connection, client_address = s.accept()
            connection.setblocking(0)
            inputs.append(connection)
            message_queues[connection] = Queue.Queue()
        else:
            data = s.recv(1024)
            if data:
                message_queues[s].put(data)
                if s not in outputs:
                    outputs.append(s)
            else:
                if s in outputs:
                    outputs.remove(s)
                inputs.remove(s)
                s.close()
                del message_queues[s]

    for s in writable:
        try:
            next_msg = message_queues[s].get_nowait()
        except Queue.Empty:
            outputs.remove(s)
        else:
            s.send(next_msg)

    for s in exceptional:
        inputs.remove(s)
        if s in outputs:
            outputs.remove(s)
        s.close()
        del message_queues[s]

Như bạn có thể thấy, có nhiều mã hơn trong máy chủ Echo chặn. Điều đó chủ yếu là vì chúng tôi phải duy trì một bộ hàng đợi cho các danh sách các ổ cắm khác nhau, tức là viết, đọc và một danh sách riêng cho các ổ cắm sai.

Tạo ổ cắm máy chủ trông giống nhau ngoại trừ một dòng:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
0. Điều này được thực hiện để làm cho ổ cắm không chặn. Máy chủ này tiên tiến hơn vì nó có thể phục vụ nhiều hơn một khách hàng. Điểm chính là trong
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1 ổ cắm:

readable, writable, exceptional = select.select(
    inputs, outputs, inputs)

Ở đây chúng tôi gọi

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2 để yêu cầu HĐH kiểm tra các ổ cắm đã cho xem họ đã sẵn sàng để viết, đọc hoặc nếu có một số ngoại lệ tương ứng. Đó là lý do tại sao nó vượt qua ba danh sách các ổ cắm để chỉ định ổ cắm nào dự kiến ​​sẽ có thể ghi, có thể đọc được và cần kiểm tra lỗi. Cuộc gọi này sẽ chặn chương trình (trừ khi một đối số thời gian chờ được thông qua) cho đến khi một số ổ cắm được thông qua đã sẵn sàng. Trong thời điểm này, cuộc gọi sẽ trả về ba danh sách với ổ cắm cho các hoạt động được chỉ định.

Sau đó, nó tuần tự lặp lại trên các danh sách đó và, nếu có ổ cắm trong đó, nó thực hiện các hoạt động tương ứng. Khi có ổ cắm máy chủ trong

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3, điều đó có nghĩa là một khách hàng mới đã đến. Do đó, nó gọi
messag = ['Hello, world', 'Test', 'anything goes here']

def client_to_server(messag,host,port,size):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    countmsg = 0
    restmsg = ''
    for msg in messag:
        strl = tmsg = msg
        if len(restmsg):
            tmsg = restmsg + ' ' + msg
        countmsg = len(tmsg)
        if countmsg <= size:
            pass
        else:
            restmsg = tmsg[size:]
            tmsg = tmsg[:size]
            #s.close()
            countmsg = len(tmsg)
            #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            #s.connect((host, port))
        print 'Sending to server msg {}'.format(tmsg)
        s.send(tmsg)
        # s.settimeout(1)
        try: 
            data = s.recv(size)
            print 'Received:', data
            if strl == data:
                print strl,data
                countmsg = 0
                restmsg = ''
        except (socket.error), e: 
            print e.args,e.message
            s.close()
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
            s.connect((host, port))
    s.close()
    if restmsg: 
        client_to_server([restmsg],host,port,size)
    return


client_to_server(messag,host,port,size)
1, thêm một ổ cắm được trả lại vào
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
3 và thêm
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6 cho các tin nhắn đến sẽ được gửi lại. Nếu có một ổ cắm khác trong đầu vào, thì một số tin nhắn đã đến và sẵn sàng để đọc để nó đọc chúng và đặt chúng vào hàng đợi tương ứng.

Đối với các ổ cắm có thể ghi, nó nhận được tin nhắn đang chờ xử lý (nếu có) và viết chúng vào ổ cắm. Nếu có bất kỳ lỗi nào trong ổ cắm, nó sẽ loại bỏ ổ cắm khỏi danh sách.

Đây là cách các ổ cắm hoạt động ở cấp độ thấp hơn. Tuy nhiên, trong hầu hết các trường hợp, không cần phải thực hiện logic ở mức thấp như vậy. Nên sử dụng một số trừu tượng cấp cao hơn như xoắn, lốc xoáy hoặc zeromq, tùy thuộc vào tình huống.

Chúng tôi hoan nghênh bạn nhìn vào trang nghiên cứu trường hợp của chúng tôi.

Tìm hiểu cách tích hợp máy chủ WebSocket được viết trong AIOHTTP vào dự án Django hiện có trong bài viết của chúng tôi. Hoặc tìm hiểu cách viết một cuộc trò chuyện đơn giản.

Làm cách nào để tạo một ổ cắm không chặn trong Python?

Trong Python, bạn sử dụng socket.setblocking (sai) để làm cho nó không chặn.socket. setblocking(False) to make it non-blocking.

Bạn có cần đóng ổ cắm Python?

Chỉ cần tắt một ổ cắm để viết nếu (1) bạn đã đưa ra quy trình và chắc chắn muốn gửi vây ngay bây giờ, hoặc (2) bạn đang tham gia vào một giao thức đọc-eos lẫn nhau sao cho cả hai đồng nghiệp đóngđồng thời.Nếu không, đóng () là đủ.Các tài liệu Python nên được sửa chữa.

Làm cách nào để tạo kết nối ổ cắm trong Python?

Lập trình ổ cắm trong hướng dẫn Python..
Nhập thư viện ổ cắm.Để sử dụng một đối tượng ổ cắm trong chương trình của bạn, hãy bắt đầu bằng cách nhập thư viện ổ cắm.....
Xây dựng các đối tượng ổ cắm.Bây giờ chúng tôi có thể tạo các đối tượng ổ cắm trong mã của chúng tôi ..
Kết nối mở và gần ..

Làm cách nào để kiểm tra xem một ổ cắm còn sống trong Python?

Sử dụng câu lệnh thử/ngoại trừ để kiểm tra ổ cắm kết nối ổ cắm.connect ((ip_address, port_number)) để kiểm tra xem ổ cắm.Ổ cắm được kết nối với ip_address tại port_number.Nếu điều này gây ra lỗi, mã trong khối ngoại trừ được thực thi.socket. connect((ip_address, port_number)) to check if socket. socket is connected to ip_address at port_number . If this raises an error, the code in the except block is executed.