search
HomeBackend DevelopmentPython TutorialDetailed introduction to Python+Socket to implement Chinese automatic reply chat function between client and server based on TCP protocol

This article mainly introduces Python+Socket to implement the Chinese automatic reply chat function between the client and the server based on the TCP protocol. It analyzes the related operation methods and precautions of Python+Socket to implement the TCP chat program with automatic reply function in the form of examples. , Friends in need can refer to the following

This article describes the example of Python+Socket implementing the Chinese automatic reply chat function between the client and the server based on the TCP protocol. I share it with you for your reference. The details are as follows:

[Tucao]

The code on the Internet kills people. It seems that the writing is conclusive. If it can be run, it will work. question.
Some friends who love codes and like to collect codes will paste and copy other people's codes when they see them. But at least you can try running it, brother

[Text]

Yesterday I modified the C/S chat program to run the UDP protocol, but the TCP protocol didn’t work. no. Various trials, various pitfalls.

After making the following modifications, it finally works:

1. Encode and decode the sent and received information respectively
2, The 10th step of the client Change the line bind to connect (This is really a big pit!!)

(This article is based on windows 7 + python 3.4)

The complete code is as follows (head guarantee , I personally tested it and it’s normal!):

Server:


##

# tcp_server.py
'''服务器'''
from socket import *
from time import ctime
HOST = '' #主机地址
PORT = 23345 #端口号
BUFSIZ = 2048 #缓存区大小,单位是字节,这里设定了2K的缓冲区
ADDR = (HOST, PORT) #链接地址
tcpSerSock = socket(AF_INET, SOCK_STREAM) #创建一个TCP套接字
tcpSerSock.bind(ADDR) #绑定地址
tcpSerSock.listen(5) #最大连接数为5
while True: #无限循环
  print('尝试连接客户端。。。')
  tcpCliSock, addr = tcpSerSock.accept() #等待接受连接
  print('链接成功,客户端地址为:', addr)
  while True:
    data = tcpCliSock.recv(BUFSIZ) #接收数据,BUFSIZ是缓存区大小
    if not data: break #如果data为空,则跳出循环
    print(data.decode())
    msg = '{} 服务器已接收 [自动回复]'.format(ctime())
    tcpCliSock.send(msg.encode())
  tcpCliSock.close() #关闭连接
tcpSerSock.close() #关闭服务器

Client:

##

# tcp_client.py
'''客户端'''
from socket import *
from time import ctime
HOST = 'localhost' #主机地址
PORT = 23345 #端口号
BUFSIZ = 2048 #缓存区大小,单位是字节,这里设定了2K的缓冲区
ADDR = (HOST, PORT) #链接地址
tcpCliSock = socket(AF_INET, SOCK_STREAM) #创建一个TCP套接字
#tcpCliSock.bind(ADDR) #绑定地址
tcpCliSock.connect(ADDR) #绑定地址
while True:
  msg = input('请输入:') #输入数据
  if not msg: break #如果 msg 为空,则跳出循环
  tcpCliSock.send(msg.encode())
  data = tcpCliSock.recv(BUFSIZ) #接收数据,BUFSIZ是缓存区大小
  if not data: break #如果data为空,则跳出循环
  print(data.decode())

[Run Screenshot]

Experimental method: Run the server first, then run the client

Then you can run the client The client can freely chat with the server:

The above is the detailed content of Detailed introduction to Python+Socket to implement Chinese automatic reply chat function between client and server based on TCP protocol. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor