【问题标题】:Connecting client to server, python将客户端连接到服务器,python
【发布时间】:2015-02-04 04:33:03
【问题描述】:

我的服务器和客户端出现问题。我需要客户端向服务器发送信息,服务器将信息发回,并且该过程再次重复。我能够让客户端连接到服务器并在第一轮发送信息,但我似乎无法弄清楚如何让服务器在使用函数 conn.shutdown(1 )。我尝试再次连接到端口,但收到一条错误消息,提示“传输端点已连接”。有什么建议吗?

【问题讨论】:

  • 为什么要在连接完成之前关机?默认情况下,刚刚关闭的套接字会在出现杂散数据包的情况下保持“正在使用”状态一段时间——这可以解决,但这是不可取的,除非在极少数情况下它是必不可少的,而你的似乎不是尽可能避免过早关闭,不是吗?

标签: python sockets client server


【解决方案1】:

尝试使用线程(多线程)-

服务器应用

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.


def clientthread(conn):
    conn.send('connected') 
    try:
        while True:        
            data = conn.recv(1024)
            processData(conn,data)
            if not data:
                break
    except Exception as ex:
        print ex
    conn.close()



while True:
   conn, addr = s.accept()    
   print 'Got connection from', addr
   thread.start_new_thread(clientthread ,(conn,))

s.close()

客户端应用

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多