In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article shows you how to carry out socket communication, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.
Using socket to realize simple one-to-one communication
Socket is a necessary functional module for network applications. Through this module, we can write the server side and client side of the program, and define the ip address and port of the server provided by the server side. After learning to use this module, we can not only drive to the network program, but also use the socket module to develop a port scanning program.
First take a look at a piece of code that creates the server side.
#-*-coding: utf-8-*-
Import socket
Import os
# define the ip and port to be bound after server startup
Ip_port = ('0.0.0.0999)
# create a socket object and specify the network type and transport protocol of the connection
Sk=sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
# bind ip and port number
Sk.bind (ip_port)
# start listening and set the maximum number of connections that can be notified
Sk.listen (5)
# keep the program running with while
While True:
# print 'server waiting...'
"
Enter accpet blocking state to wait for a connection request from the client
Save the connection status and address of the client
"
Conn,addr = sk.accept ()
Print addr
# if a client sends a request, it will only accept 1024 bytes of content each time. Note that recv () is also blocked.
Client_data = conn.recv (10240)
# print the string received from the client
Print client_data-client ip address
# send a string to the client
Conn.sendall ("I `m server")
# close the connection
Conn.close ()
Client code
#-*-coding: utf-8-*-
Import socket # specify the ip address and port number of the server ip_port = ('127.0.0.1) # create a socket instance If the parameter is left empty, the ipv4 protocol is used to transmit sk = socket.socket () # initiate a connection to the server side sk.connect (ip_port) # send a message to the server side sk.sendall ("I `m client") # receive the server side feedback server_reply = sk.recv (1024) # print the server side feedback print server_reply # close the connection sk.close ()
Through the operation of the above two pieces of code, we realize the communication between the server side and the client side.
You can get the following running result on the server side, and return to the waiting state after receiving the client request.
Server waiting...
I `m client
Server waiting...
A similar result was seen on the client side, and the program was exited after successfully receiving the message from the server side.
Click (here) to collapse or open
I `m server
Expansion: parse the client's log files in real time and send them to the server for saving
Server end rewrite
#-*-coding: utf-8-*-
Import socket
Import os
Def save_to_txt (addr,data):
Path='/tmp/'+addr+'/slow.log'
File_path = os.path.split (path)
If not os.path.exists (file_path [0]):
Os.makedirs (file_path [0])
Print 'directory created successfully'
If len (data) > 0:
Try:
With open (path.encode ('utf-8'),' ab') as f:
Data = data+ "\ n"
F.write (data.encode ('utf-8'))
Except:
Print 'data insertion failed'
Else:
Print'no data'
# define the ip and port to be bound after server startup
Ip_port = ('0.0.0.0999)
# create a socket object and specify the network type and transport protocol of the connection
Sk=sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
# bind ip and port number
Sk.bind (ip_port)
# start listening and set the maximum number of connections that can be notified
Sk.listen (5)
# keep the program running with while
While True:
# print 'server waiting...'
"
Enter accpet blocking state to wait for a connection request from the client
Save the connection status and address of the client
"
Conn,addr = sk.accept ()
Print addr
# if a client sends a request, it will only accept 1024 bytes of content each time. Note that recv () is also blocked.
Client_data = conn.recv (10240)
# print the string received from the client
Print client_data
Save_to_txt (addr [0], client_data)-pick up and write to the log file
# send a string to the client
Conn.sendall ("I `m server")
# close the connection
Conn.close ()
Client rewriting
#-*-coding: utf-8-*-
Import socket
Def sendtxt (line):
Ip_port = ('192.168.2.136)
# create a socket instance. If the parameter is left empty, it will be transmitted over tcp using ipv4 protocol.
Sk = socket.socket ()
# initiate a connection to the server
Sk.connect (ip_port)
# send a message to server
Sk.sendall (line)
# receive feedback from server after sending
Server_reply = sk.recv (10240)
# print the feedback from the server
Print server_reply
# close the connection
Sk.close ()
Import fileinput
Import time
Import os
Target_file = 'log.txt'
Init_flag = True # initial loader
Record_count = 0
While True:
If init_flag:
# read the whole file
# for eachline in fileinput.input (target_file):
# print eachline
# record_count + = 1
Total_count = os.popen ('wc-l% s'% target_file). Read (). Split () [0]
Total_count = int (total_count)
Record_count = total_count
Init_flag = False
Else:
# if the total number of lines is less than the current line, then the file is considered to be updated and read from the first line.
Total_count = os.popen ('wc-l% s'% target_file). Read (). Split () [0]
Total_count = int (total_count)
If total_count
< record_count: record_count = 0 for eachline in fileinput.input(target_file): line_no = fileinput.filelineno() if line_no >Record_count:
If len (eachline.strip ('\ n')) > 0:
Print eachline.strip ('\ n')
Sendtxt (eachline.strip ('\ n'))-- send
Record_count + = 1
Else:
Sendtxt ('')
Record_count + = 1
The above content is how to communicate with socket. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.