1.socket(family, type)
创建套接字对象,family=socket.AF_INET, type=socket.SOCK_STREAM(TCP)/socket.SOCK_DGRAM(UDP)
2.s.bind((host, port))
绑定套接字s以接收来自主机host在端口号port上的连接。host可以是空字符串(''),表示接受来自任何主机的连接。
3.s.listen(maxpending)
监听到该套接字的连接尝试,任何时候允许最多maxpending个排队的连接尝试。
4.s.accept()
s必须是TCP类型,接收一个连接请求并返回一个数据对(s1, (ipaddress, port))。s1是一个新连接的套接字。调用之前必须已经调用了s.bind和s.listen方法。
5.s.recv(bufsize)
从套接字接收最多bufsize个字节的数据,并返回一个由接收的数据组成的字符串。
6.s.sendall(string)
在套接字上按字节发送string字符串,该方法将会阻塞,直到所有的字节都被发送。
7.s.close()
关闭套接字。
8.s.recvfrom(bufsize)
从套接字接收最多bufsize个字节的数据,并返回一个元组(data, (ipaddr, port))。在使用UDP时很有用,可以接收来自多个发送方的数据。
9.s.sendto(string, (host,port))
在套接字上将string字符串按照字节发送到目的host和port上,并返回发送的字节数n。对UDP很有用,可以将数据发送到多个目的地。
10. s.connect((host, port))
将套接字s连接到给定host和port指定的服务器上。
TCPServer:
# _*_ coding:utf-8 _*-
import socket
if __name__ == "__main__":
ser_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ser_soc.bind(('',8881))
ser_soc.listen(5)
try:
while True:
new_soc, address = ser_soc.accept()
print "Connected from", address
while True:
receivedData = new_soc.recv(1024)
if not receivedData:
break
new_soc.sendall(receivedData)
new_soc.close()
print "Disconnected from", address
finally:
ser_soc.close()
TCPClient:
# _*_ coding:utf-8 _*_
import socket
if __name__ == "__main__":
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect(('localhost',8881))
print "Connected to server"
data = '''Hi,Tim.
I'm a programmer.
Googbye.'''
for line in data.splitlines():
soc.sendall(line)
print 'Send:',line
response = soc.recv(1024)
print 'Received:',response
soc.close()
UDPServer:
# _*_ coding:utf-8 _*_
import socket
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('',8881))
try:
while True:
data, address = sock.recvfrom(1024)
print "Datagram from:", address
sock.sendto(data,address)
finally:
sock.close()
UDPClient:
# _*_ coding:utf-8 _*_
import socket
if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = '''Hi,Tim.
I'm a programmer.
Googbye.'''
for line in data.splitlines():
sock.sendto(line,('localhost',8881))
print "Send:",line
response = sock.recv(1024)
print "Received:",response
sock.close()