Build the service side
1. Import the module
Import socket
2. Create a Socket object
Sock=socket. Socket (socket_family,socket_topy)
3. Binding port
Sock.bind (("", 8000))
4. Setting Up Monitoring
Sock.listen (5)
5. Acceptance of information
Con,add=sock.accept ()
Con: Accept the Sock object, accept the message sent by the other party
ADD:IP recognition
Con.send ("Hello,i am Your Server")
6. Close the socket You
Sock.close ()
Setting up the socket TCP client
1. Import the module
Import socket
2. Create socket object, socket is a class
Sock=socket. Socket (socket_family,socket_topy)
3. Connect to the server
4. Acceptance of information
5. Close the socket
Sock.close () service-side code
#coding: UTF-8
#第一种, after sending hello on both sides of the link, respectively, disconnect
Import socket
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind (("", 8000)) #绑定所有IP
Print "This is socket_server:127.0.0.1:8000"
Sock.listen (5)
Con,add=sock.accept ()
Print con
Print add
Print "%s is connected"%add[0]
Print CON.RECV (512)
Con.send ("Hello I am Your server")
Sock.close ()
#第二种, both sides of the text interaction
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind ("127.0.0.1", 8000))
Sock.listen (5)
Con,add=sock.accept ()
While true:
RECVS=CON.RECV (512)
Print Recvs
If recvs== "Break":
Break
Sends=raw_input ("..")
Sock.send (Sends)
If sends== "Break":
Break
Sock.close ()
#第三种: Client sends break, server enters passive blocking accept
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind ("127.0.0.1", 8000))
Sock.listen (5)
While true:
Con,add=sock.accept ()
While true:
RECVS=CON.RECV (512)
Print Recvs
If recvs== "Break":
Break
Sends=raw_input ("..")
Python Learning notes (socket)