Server side:
# coding:gb2312
#socket Server Side
#获取socket构造及常量
From socket Import *
# ' on behalf of server ' localhost '
MyHost = ' '
#在一个非保留端口号上进行监听
MyPort = 50007
#设置一个TCP Socket Object
Sockobj = socket (af_inet, SOCK_STREAM)
#绑定它至端口号
Sockobj.bind ((MyHost, MyPort))
#监听, allow 5 links
Sockobj.listen (5)
#直到进程结束时才结束循环
While True:
#等待下一个客户端连结
Connection, address = sockobj.accept ()
#连结是一个新的socket
print ' Server connected by ', address
While True:
#读取客户端套接字的下一行
data = CONNECTION.RECV (1024)
print "Reply:", data
#如果没有数据的话, then jump out of the loop
Message = Raw_input ("QQ chat:")
Connection.send (Message)
#当socket关闭时eof
Connection.close ()
Client side:
# coding:gb2312
Import Sys
From socket Import *
ServerHost = ' 192.168.159.3 '
ServerPort = 50007
#发送至服务端的默认文本
message = [' Hello ']
#如果参数大于1的话, the service end of the connection is the first parameter
If Len (SYS.ARGV) > 1:
ServerHost = sys.argv[1]
#如果参数大于2的话, the text of a link is the second argument
If Len (SYS.ARGV) > 2:
Message = Sys.argv[2:]
#建立一个tcp/IP Socket Object
Sockobj = socket (af_inet, SOCK_STREAM)
#连结至服务器及端口
Sockobj.connect ((ServerHost, ServerPort))
While True:
Message = Raw_input ("QQ chat:")
Sockobj.send (Message)
#从服务端接收到的数据, capped at 1k
data = SOCKOBJ.RECV (1024)
#确认他是引用的, it's ' X '.
print ' reply: ', repr (data)
#关闭套接字
Sockobj.close ()
Python's character interface QQ