我最近度假回来了,我的基本python 2套接字服务器现在无法通过LAN与客户端通信。服务器在mac上,客户端是我的raspberry pi或windows 7机器。我在这里简化了服务器和客户端代码,给出了一个示例:
服务器
import socket
from thread import *
HOST = socket.gethostname()
print HOST
PORT = input ("Enter the PORT number (1 - 10,000)")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print "Socket Created"
s.bind((HOST, PORT))
print "Socket Bind Complete"
s.listen(10)
print "Socket now listening"
#Sending message to connected client
#This only takes strings (words
while True:
#Wait to accept a connection - blocking call
connection, addr = s.accept()
print "Connection Established!"
connection.send("Welcome to the server. Type something and hit enter\n")
#loop so that function does not terminate and the thread does not end
while True:
#Receiving from client
data = connection.recv(1024)
if not data:
break
connection.sendall(data)
print data
connection.close()
s.close()
客户端
import socket #for sockets
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
#Get host and port info to connect
host = raw_input("HOST >>> ")
port = 2468
s.connect((host, port))
while True:
#Send some data to the remote server
message = raw_input(">>> ")
#set the whole string
s.sendall(message)
reply = s.recv(1024)
print reply
问题
这里发生什么事情?我正在获得本地IP,但脚本仍然无法通信。这会不会是操作系统的问题?
更多信息
我的Mac防火墙关闭了。我将检查Raspberry Pi Stackexchange站点,看看PI是否有防火墙。
一旦我测试了我的windows机器,我会添加更多的信息。
发布于 2013-03-25 00:27:40
在本地运行这两个脚本,它们可以在我的机器上连接和通信。您正面临一个网络问题,这个问题应该很容易调试。
SYN
数据包,但服务器将无法使用SYN|ACK
数据包进行应答。如果您看到SYN
数据包到达服务器,请尝试完全关闭服务器的防火墙,然后再试一次。否则,客户端将被禁止对外通信(不太可能),您将需要关闭它的防火墙。发布于 2013-09-23 03:42:24
您的代码运行良好,不过,我做了一些小更正,并在代码中的注释中对它们进行了解释:
服务器:
import socket
from thread import *
# 1.Gets the local ip/ip over LAN.
HOST =socket.gethostbyname(socket.gethostname())
print HOST
# 2.Use port no. above 1800 so it does not interfere with ports already in use.
PORT =input ("Enter the PORT number (1 - 10,000)")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print "Socket Created"
s.bind((HOST, PORT))
print "Socket Bind Complete"
s.listen(10)
print "Socket now listening"
while True:
connection, addr = s.accept()
print "Connection Established!"
connection.send("Welcome to the server. Type something and hit enter\n")
while True:
data = connection.recv(1024)
if not data:
break
connection.sendall(data)
print data
connection.close()
s.close()
客户端:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
host = raw_input("HOST >>> ")
# 3. Use the same port no. entered on server.py as the client binds to the
# same port
port = input ("Enter the PORT number (1 - 10,000)")
s.connect((host, port))
while True:
message = raw_input(">>> ")
s.sendall(message)
reply = s.recv(1024)
print reply
上面的代码对我来说很好,我相信它对你也是一样的,因为我也经历过同样的麻烦。发现的bugs -我把它们放在代码中的注释中--请看一看。
干杯……!
https://stackoverflow.com/questions/15608189
复制相似问题