#-*-Coding:utf-8-*-
# python:2.x
__author__ = ' Administrator '
#socket Object Sub-server and client
# The main steps of the server are as follows
"""
1 initializing a socket
Socket () 2 parameters, one is af_inet:socketfamily, the other is sock_stream represents TCP Connection
Bind (addr) binds an address, here the addr is a map, has HOST and PORT2 a parameter
Listem () listens for advice, indicating that it can listen to a few requests
Accept () accepts a socket, returns a socket object and address for the client, and then operates via a traveler return object, including message feedback, etc.
Close () closes the socket resource, including closing the Accept client socket object and the server socket object
"""
# For example, I'm not running the program on this side
From socket Import *
From time Import *
def serv (host= ", port=12456):
Addr= (Host,port)
Tcps=socket (Af_inet,sock_stream)
Try
Tcps.bind (ADDR)
Tcps.listen (5)
Except Exception,e:
print ' error:%s '% (e)
While True:
print ' Waiting for connection ... '
Tcpli,addr=tcps.accept ()
print ' connection form ... ', addr
While True:
bufsiz=2048
DATA=TCPLI.RECV (Bufsiz)
If not data:
Break
Tcpli.send (' [%s],%s '% (CTime (), data))
Tcpli.close ()
Tcps.close ()
# Client:
"""
1. also initialize a socket:
2. establish connections to the server: there can be connect () and create_connection () two functions, with two parameters: first address Addr, the other one is timeout .
3.send(data) sends a socket data
4.RECV () accepts a socket data. The parameter can be the size of the accepted data volume
5.close ()
"""
Import socket
host= ' localhost '
port=21568
bufsiz=1024
Addr= (Host,port)
Tcpclisock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Tcpclisock.connect (ADDR)
While True:
Data=raw_input (' > ')
If not data:
Break
Tcpclisock.send (data)
DATA=TCPCLISOCK.RECV (Bufsiz)
If not data:
Break
Print data
Tcpclisock.close ()
Note: Other points: the socket on the server does not have recv(data), so you want to accept and send the data via accept () Returns the socket object to be manipulated.
Python-socket Basic Learning 2