最近在调Python通过Socket Client连接C#的Socket Server,但是Server端能检测到连接,却收不到数据,这个问题困扰了几个小时,最后是因为Python这边发送完数据,直接关闭了连接,最好是sleep一点点时间再关闭Socket,这样就能正常收到数据了。
#/usr/bin/env python
# -*- coding: utf-8 -*-
# C# Socket Server 收不到数据
# 说明:
# 最近在调Python通过Socket Client连接C#的Socket Server,但是Server端能检测到连接,
# 却收不到数据,这个问题困扰了几个小时,最后是因为Python这边发送完数据,直接关闭了
# 连接,最好是sleep一点点时间再关闭Socket,这样就能正常收到数据了。
#
# 2016-11-09 深圳 南山平山村 曾剑锋
...
class Network(threading.Thread):
def connect(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((configures.remoteConfig.ip, configures.remoteConfig.port))
def sendData(self, data):
if self.sock != None:
self.sock.send(data)
def disconnect(self):
if self.sock != None:
self.sock.close()
def run(self):
self.connect()
self.sendData(bytes(self.data, encoding = "utf8"))
time.sleep(0.1%10) # 这里一定要设定一个延时
self.disconnect()