Python Socket Programming

Source: Internet
Author: User

1. Directly on the code

server:__author__='Alex'#Coding:utf-8ImportSocketip_port= ('127.0.0.1', 8000) SK=socket.socket () sk.bind (ip_port) sk.listen (5)Print("Server start ...") whiletrue:conn,addr=sk.accept () whileTrue:Try: Recv_data= Conn.recv (1024)            ifLen (recv_data) = = 0: break        exceptException as E:Print("accidental Interruption")             break        Print(str (recv_data,"UTF8")) Send_data= Input (">>>>>>") Conn.sendall (bytes (send_data,"UTF8") ) Conn.close ()
######################################################## #client:
__author__='Alex'#Coding:utf-8ImportSocketip_port= ('127.0.0.1', 8000) SK=socket.socket () sk.connect (ip_port)Print("client-initiated ...") whileTrue:send_data= Input (">>>>>>>") ifSend_data = ='Exit': breaksk.send (bytes (send_data,"UTF8")) Recv_data= Sk.recv (1024) Print(str (recv_data,"UTF8") ) Sk.close ()

In this program to do a few notes: 1, if the client sends exit, then the server will receive an empty string, because you can determine the length of the received string to know whether the client exits, 2, if the client is terminated by the way the program is closed, Then the server will receive a exception, then the service side to do the exception handling (in the Windows environment), in the case of linux, the termination of the program will cause the service side to receive an empty String.

Python Socket Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.