except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue
try:
print "连接来自:",clientsock.getpeername()
while 1:
data=clientsock.recv(4096)
if not len(data):
break
print clientsock.getpeername()[0]+':'+str(data)
clientsock.sendall(data)
clientsock.sendall("nI get it!n")
t=raw_input('input the word:')
clientsock.sendall(t)
except (KeyboardInterrupt,SystemExit):
raise
except:
traceback.print_exc()
try:
clientsock.close()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
客户端:tcpclient.py
# -*- coding: cp936 -*-
##tcp客户端,首先输入服务器ip地址,然后输入信息,回车后会得到服务器返回信息,然后等待服务器向其发送信息后退出。
##@小五义
import socket,sys
port=12345
host=raw_input('输入服务器ip:')
data=raw_input('输入要发送的信息:')
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host,port))
except:
print '连接错误!'
s.send(data)
s.shutdown(1)
print '发送完成。'
while 1:
buf=s.recv(4096)
if not len(buf):
break
sys.stdout.write(buf)
执行结果:
客户端输入hello,服务器端输入ok,具体显示结果是:
服务器端:
连接来自:('127.0.0.1',1945)
127.0.0.1:hello
Input the world:ok
客户端:
输入服务器ip:127.0.0.1
输入要发送的信息:hello
发送完成。
hello
I get it!
ok
3、UDP服务器
UDP服务器建立与TCP相类似,具体比较如下:










