Python TCP 服务器套接字 [英] Python TCP server socket

查看:54
本文介绍了Python TCP 服务器套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 打开服务器套接字

I'm trying to open server socket using python

我正在使用的代码等待连接并暂停循环,直到尝试执行此行时实现下一个连接 >>

the code that I'm using wait for connection and pause the loop until the next connection achieved when its trying to execute this line >>

连接,client_address = sock.accept()

connection, client_address = sock.accept()

但我不需要暂停循环

有没有什么方法可以让代码在没有连接的情况下跳过这一行继续循环

Is there any method to make the code skip this line and continue the loop if there is no connection

代码:

服务器

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)

# Listen for incoming connections
sock.listen(5)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()
	
    try:
        print >>sys.stderr, 'connection from', client_address

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print >>sys.stderr, 'received "%s"' % data
            if data:
                print >>sys.stderr, 'sending data back to the client'
                connection.sendall(data)
            else:
                print >>sys.stderr, 'no more data from', client_address
                break
            
    finally:
        # Clean up the connection
        connection.close()	

客户

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)


try:
    
    # Send data
    message = 'This is the message.  It will be repeated.'
    print >>sys.stderr, 'sending "%s"' % message
    sock.sendall(message)

    # Look for the response
    amount_received = 0
    amount_expected = len(message)
    
    while amount_received < amount_expected:
        data = sock.recv(32)
        amount_received += len(data)
        print >>sys.stderr, 'received "%s"' % data

finally:
    print >>sys.stderr, 'closing socket'
    sock.close()
	

推荐答案

您可以将套接字设置为非阻塞,如果没有连接就绪则返回错误而不是无限阻塞

You can set the socket to be non blocking, this will then return an error if there is no connection ready rather than blocking indefinetly

sock.setblocking(False)
try:
    connection, client_address = sock.accept()
except:
    print 'No Connection'

这篇关于Python TCP 服务器套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆