Python使用socket模块实现简单tcp通信

时间:2022-09-15 11:27:12

正文开始:

服务器端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 再来简单的测试,这个是服务器端
import socket
import sys
 
BUF_SIZE = 1024
ip_port = (r"127.0.0.1", 11552)
 
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 先拿到套接字,指定个ipv4以及流式数据包
my_socket.bind(ip_port) # 绑定
my_socket.listen(2)
 
# 循环等待客户端连接
while True:
  print("waiting for client..")
  conn, address = my_socket.accept()
  print("connect from .." + str(address))
 
  # 循环接受
  while True:
    ret = conn.recv(BUF_SIZE)
    print("server receive data:" + str(ret))
 
    if "END" in str(ret):
      print("clent's gonna be offline.")
      conn.send(bytes("BYE", encoding="utf-8"))
      my_socket.close()
      sys.exit()
    else:
      conn.send(bytes("server copy", encoding="utf-8"))

客户端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 这个是客户端
import socket
 
BUF_SIZE = 1024
ip_port = (r"127.0.0.1", 11552)
 
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.connect(ip_port)
 
while True:
  data = input(">>>")
 
  my_socket.send(bytes(data, encoding="utf-8"))
  recieve_data = my_socket.recv(BUF_SIZE)
  print("client receive data = " + str(recieve_data))
  if "BYE" in str(recieve_data):
    print("server disconnect!")
    break

运行方法:

一个利用windows的cmd,直接输入命令:python server.py运行服务器

一个利用pycharm直接运行client.py

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/qihuanye-229110/p/13439886.html