无论是tcp协议的socket还是udp协议的socket,都是通过socket.socket(socket.AF_INET,socket.SOCK_STREAM/SOCK_DGRAM) 创建
第一个参数一般都是填写socket.AF_INET
第二个参数
Tcp: SOCK_STREAM
Udp:SOCK_DGRAM
简单代码:
client.py
import socket
import time
if __name__=='__main__':
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
addr=('localhost',2000)
sock.connect(addr)
time.sleep(2)
try:
while True:
sock.send(raw_input('>>'))
buff=sock.recv(1024)
print 'get: %s %s' % (buff,time.ctime())
except Exception,e:
print "Error:",e
sock.close()
services.py
import socket
import datetime
if __name__=='__main__':
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('127.0.0.1',2000))
sock.listen(5)
while True:
connection,address=sock.accept()
connection.settimeout(10000)
while True:
try:
buf=connection.recv(1024)
print 'get: %s %s' % (buf,datetime.datetime.now())
if buf=='exit':
break
connection.send(raw_input('>>'))
except socket.timeout:
print 'time out'
connection.close()
Udp协议与tcp协议差不多,只是关键字不同而已