Initial socket Programming (Python)

Source: Internet
Author: User

Both sides of the communication need to have a server and a client, so separate to write code.

So I created two PY programs, the first one is the server: iserver.py and client iclient.py

Service side:

#coding: Utf-8
From socket Import *
s = socket (af_inet,sock_stream) #建立一个服务器socket对象, similar to the process of buying a phone, af_inet is the socket type of the IPV4 network protocol, and Sock_stream is the TCP protocol
S.bind ((', 6666)) #bind为绑定, the first "is the address, and here is the local so do not write the address number, and 6666 is the port number

S.listen (1) #设置服务器socket的请求队列长度
S.accept ()
SOCK,ADDR = S.accept () # #开始监听服务器socket端口, multiple threads can be monitored together
Print "Connect by", addr
Sock.send (' welcome,this is server ')

Text = SOCK.RECV (1024)
Print text
Sock.close ()
S.close ()

Client:

#coding: Utf-8
From socket Import *

C=socket (Af_inet,sock_stream)
C.connect (' 127.0.0.1 ', 6666)
Text = C.RECV (1024)
Print text

C.send (' Hello,i am client ')

C.close ()

You can run it in CMD. Can implement a word of communication process, but currently limited to local testing, and then I will step by step to achieve more complex features, continuous efforts.

Initial socket Programming (Python)

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.