程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python TCP server based on socket

編輯:Python
'''
be based on socket Realized TCP Server side
'''
import socket
# establish socket object
server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# If the server is one-time , If the server restarts immediately after it is finished, an error will appear , The reason is that the address and port are not released
# OSError: [Errno 48] Address already in use
# If you want to release immediately , Set it up socket Options
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
# binding IP And port , If you're binding IP Not given at IP, The default is to bind to local IP
server_socket.bind(('',7777))
# Set listening ( Maximum number of monitors ), After setting, the server will enter the passive mode , Unable to actively connect to the client , Can only passively wait for the client to connect
server_socket.listen(128)
# Wait for the client to connect , After connecting , The function returns the client's Socket Object and address information
client_socket,ip_port=server_socket.accept()
print(f' client {ip_port[0]} The use of port {ip_port[1]} Successful connection ...')
# Receive client data
data=client_socket.recv(1024)
# View the length of data sent by the client
if len(data)!=0:
data=data.decode('gbk')
print(f' client {ip_port[0]} The use of port {ip_port[1]} Send yes data yes {data}')
else:
print(f' client {ip_port[0]} The use of port {ip_port[1]} Close the connection ')
# Send data to the client
data=' Hello '.encode('gbk')
client_socket.send(data)
# Close client
client_socket.close()
# Turn off the server
server_socket.close()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved