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)