Python Socket通信示例:实现客户端与服务器的字符串回显

林见深
林见深
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍使用Python socket模块构建简单的客户端-服务器通信程序。服务器监听指定端口,接收客户端发送的字符串后将其回显,并支持在连接建立后向客户端发送多条消息。代码展示了连接建立、数据发送与接收的基本流程,适用于学习Python网络编程基础。

Python Socket通信示例:实现客户端与服务器的字符串回显

该程序的功能是从客户端向服务器发送一个字符串,服务器在接收到该字符串后,将其重新发送给客户端。此外,在连接成功建立之后,服务器还可以向客户端发送任意数量的字符串。

客户端实现如下:

其中,10.248.27.23是我电脑的IP地址。

客户端代码实现


import socket, sys
host = '10.248.27.23'
# host = raw_input("Plz imput destination IP:")
# data = raw_input("Plz imput what you want to submit:")
port = 51423
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
  s.connect((host, port))
except socket.gaierror, e:
  print "Address-related error connecting to server: %s" %e
  sys.exit(1)
except socket.error, e:
  print "Connection error: %s" %e
  sys.exit(1)
data = raw_input("Plz imput what you want to submit:")
s.send(data)
s.shutdown(1)
print "Submit Complete"
while 1:
    buf = s.recv(1024)
    sys.stdout.write(buf)

服务器端实现如下:

服务器端代码实现


import socket, traceback
host = ''
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
print "done"
while 1:
  #when connect error happen, skip the error
  try:
    ClientSock, ClientAddr = s.accept()
  except KeyboardInterrupt:
    raise
  except:
    traceback.print_exc()
    continue
  #Get informaion form client and reply
  try:
    print "Get connect from ", ClientSock.getpeername()
    data = ClientSock.recv(1024)
    print "The information we get is %s" % str(data)
    ClientSock.sendall("I`ve got the information: ")
    ClientSock.sendall(data)
    while 1:
      str = raw_input("What you want to say:")
      ClientSock.sendall(str)
      ClientSock.sendall('\n')
  except (KeyboardInterrupt ,SystemError):
    raise
  except:
    traceback.print_exc()
  #Clocs socket
  try:
    ClientSock.close()
  except KeyboardInterrupt:
    raise
  except:
    traceback.print_exc()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。如果你想了解更多相关内容请查看下面相关链接

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表