我一直在玩弄 Python 套接字,希望了解如何更好地完成网络编程。现在我正在尝试设置一个连接到服务器的客户端,并且可以在关闭之前向它发送任意数量的消息。我仍然不太了解所有内容,我只能让它发送一条消息。对于有套接字编程经验的人来说,这可能是显而易见的。有人可以向我解释如何让它发送多条消息吗?也许为我提供一个很好的资源来解释连接、绑定、关闭、接收和所有主要的套接字功能是如何工作的?(我发现的大多数资源只是告诉我何时使用它们。)
客户
# !usr/bin/python
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connect to server
s.connect((host,port))
while message != "/e":
#Send Data
message = raw_input("Send >> ")
try:
s.sendall(message)
except socket.error, msg:
print "ERROR %s"%(msg[1])
print "Failed to send."
s.close()
if __name__ == "__main__":
main()
服务器
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
s = socket.socket()
class BoServer:
def __init__(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
def bind(self):
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
def run(self):
while True:
s.listen(10)
print "Socket Listening"
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
income = conn.recv(4096)
if income != "":
print income
def main():
serv = BoServer()
serv.bind()
serv.run()
if __name__ == "__main__":
main()