简体   繁体   English

基本TCP连接

[英]Basic TCP Connection

I am trying to control some test equipment with a TCP connection. 我正在尝试通过TCP连接控制某些测试设备。 The equipment comes with software that you are able to control over TCP. 该设备随附了可以控制TCP的软件。 Basically, you can input the IP address and port of the client computer and there is also an indicator light that shows when there is an open listening session on that port (this is all on the equipment software interface) 基本上,您可以输入客户端计算机的IP地址和端口,并且还有一个指示灯,用于显示该端口上何时存在打开的监听会话(这全部在设备软件界面上)

I have tested this using SocketTest3 (free software) and am able to start a listening session as well as send commands from another computer. 我已经使用SocketTest3(免费软件)对其进行了测试,并且能够启动侦听会话以及从另一台计算机发送命令。 Now, I want to control the equipment with Python. 现在,我想用Python控制设备。 I am running the code for the server and client on the same machine as the test equipment (using local IP address). 我在与测试设备相同的机器上运行服务器和客户端的代码(使用本地IP地址)。 When I simply run the code (with the equipment software closed) I am able to send, receive, and print the messages I send. 当我简单地运行代码(在关闭设备软件的情况下)时,我能够发送,接收和打印我发送的消息。 When I have the equipment software open (necessary for control) I am able to start a listening session (indicator light shows up on equipment software), but nothing happens (no errors and nothing received) when I send commands. 打开设备软件(需要控制)后,我可以启动侦听会话(设备软件上的指示灯亮起),但是发送命令时什么也没发生(没有错误,没有收到任何东西)。 The messages are also not sent back to the client to print. 消息也不会发送回客户端进行打印。

Any ideas? 有任何想法吗? It's probably something very simple that I'm missing. 我可能想念的很简单。

Server code: 服务器代码:

import sys
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCP_IP = '127.0.0.1'
TCP_PORT = 8001
s.bind((TCP_IP, TCP_PORT))
s.listen(5)

connection, client_address = s.accept()
BUFFER_SIZE  = 20
print 'Address: ', client_address

while 1:
    print "receiving..."
    data = connection.recv(BUFFER_SIZE)
    print data
    if not data: break
    print "received data:", data
    connection.send(data) # echo
connection.close()

Client code: 客户代码:

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 8001 
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))

print "sending message..."
s.sendall('ST<CR>') # Send command
print "receiving message..."
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data

For those wondering what is missing from camerausb's code, I think he was not seeing anything from the client's print statement because he did not use repr() to format the data. 对于那些想知道camerausb代码中缺少什么的人,我认为他没有从客户端的打印语句中看到任何内容,因为他没有使用repr()格式化数据。 I had a similar problem, but this worked for me: 我有一个类似的问题,但这对我有用:

print 'Received', repr(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM