"Python sockets" socket programming

Source: Internet
Author: User

1. Client

Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #建立TCP连接
S.connect (' 192.168.1.109 ', 1111) #连接服务器, requires the server's address and port
Print (' This is the client! ‘)
While True:
t = input () #输入
S.send (T.encode (' UTF8 ')) #发送t的utf8格式数据
If T = = ' exit ': #如果发现是exit
Break
t= ' server: ' +s.recv (1024x768). Decode (' UTF8 ') #收到服务器来的数据
If T = = ' exit ': #如果服务器来的是exit, exit the loop
Break
Print (t)
Print (' Disconnect! ‘)
S.close ()

2. Service-side

Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #TCP通讯 to ensure that data reaches
S.bind ((' 192.168.1.109 ', 1111)) #自身服务器地址, with open ports
S.listen (5) #监听数
Print (' This is the server! ‘)
Print (' Please wait ... ')
Connect,address = s.accept () #接受客户端的连接:
Print ("Connection Successful! ")
While True:
t = ' client: ' +connect.recv (1024x768). Decode (' UTF8 ') #服务端先接收信息, and parse UTF8
If T = = ' exit ': #如果接收到的是exit
Break #退出循环
Print (t) #不然就打印出来信息
t = input () #然后服务器输入
If T = = ' exit ': #如果是exit, exit the loop
Break
Connect.send (T.encode (' UTF8 ')) #使connect收发数据 (sent to connected socket data)
Print (' Disconnect! ‘)
S.close ()
#先使服务端运行, after running the client

"Python sockets" 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.