回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我开始尝试编写pythontcp套接字侦听器。在</p>
<p>我有一个调制解调器连接到我的Debian盒子,每60秒报告一次GPS NMEA语句。现在我只想运行一个python程序来接收和打印这些GPS消息。在</p>
<p>调制解调器配置为使用端口8764上的TCP将消息发送到Debian IP。在</p>
<p>我创建了一个简单的程序(基于<a href="http://pymotw.com/2/socket/tcp.html" rel="nofollow">http://pymotw.com/2/socket/tcp.html</a>):</p>
<pre><code>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', 8764)
sock.connect(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print 'waiting for a connection'
connection, client_address = sock.accept()
try:
print 'connection from', client_address
while True:
data = connection.recv(8)
print 'received: %s' % data
except:
print 'error'
</code></pre>
<p>当我运行这个脚本时袜子。接受(),在“等待连接”之后</p>
<p>我不确定这是Python代码中的问题,还是没有在Debian中正确配置TCP套接字。在</p>
<p>运行<code>netstat -tulpn</code>我得到:</p>
^{pr2}$
<hr/>
<p>更新:</p>
<p>来自<code>sudo tcpdump -i any port 8764</code>的输出</p>
<pre><code>tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 65535 bytes
12:51:27.953851 IP 192.168.0.1.3202 > myHostName.local.8764: Flags [S], seq 1679917557, win 5200, options [mss 1300,sackOK,TS val 5634364 ecr 0,nop,wscale 1], length 0
12:51:27.953896 IP myHostName.local.8764 > 192.168.0.1.3202: Flags [R.], seq 0, ack 1679917558, win 0, length 0
12:51:57.970515 IP 192.168.0.1.3203 > myHostName.local.8764: Flags [S], seq 1717423935, win 5200, options [mss 1300,sackOK,TS val 5664379 ecr 0,nop,wscale 1], length 0
12:51:57.970561 IP myHostName.local.8764 > 192.168.0.1.3203: Flags [R.], seq 0, ack 1717423936, win 0, length 0
12:52:08.981407 IP 192.168.0.1.3204 > myHostName.local.8764: Flags [S], seq 1728493476, win 5200, options [mss 1300,sackOK,TS val 5675389 ecr 0,nop,wscale 1], length 0
12:52:08.981451 IP myHostName.local.8764 > 192.168.0.1.3204: Flags [R.], seq 0, ack 1728493477, win 0, length 0
12:52:39.064132 IP 192.168.0.1.3626 > myHostName.local.8764: Flags [S], seq 1770515829, win 5200, options [mss 1300,sackOK,TS val 5705470 ecr 0,nop,wscale 1], length 0
12:52:39.064175 IP myHostName.local.8764 > 192.168.0.1.3626: Flags [R.], seq 0, ack 1770515830, win 0, length 0
</code></pre>
<p>192.168.0.1是GPS调制解调器的地址</p>
<p>所以似乎每隔30秒就会有一次握手。调制解调器不断跳转到新端口,可能是因为先前的通信尝试失败。在</p>
<hr/>
<p>更新:</p>
<p>出于某种原因,我的服务器地址定义出了问题。在</p>
<p>用<code>server_address = ('localhost',8764)</code>与{<cd4>}交换解决了这个问题</p>