您的服务器侦听正确的端口,但需要适当的数据处理。研究下面的代码,你会对此有一个很好的理解。
from socket import *
import string
from time import ctime
HOST = '127.0.0.1'
PORT = 8087
BUFSIZ = 1024
ADDR = (HOST, PORT)
ssock = socket(AF_INET, SOCK_STREAM)
ssock.bind(ADDR)
ssock.listen(5)
try:
while True:
c = 1
print 'Waiting for a connection...'
csock, addr = ssock.accept()
hostname, aliases, addresses = gethostbyaddr(addr[0])
lip, lport = ssock.getsockname()
print '''
Connected ...
Remote Host : %s
Remote host IP : %s
Remort Port : %d
Connected time : %s
Local IP : %s
Local Port : %d \n''' % (hostname , addr[0], addr[1], ctime(), lip, lport)
while True:
data = csock.recv(BUFSIZ)
if data == 'q':
break
elif data == 'shut':
ssock.close()
break
elif data == ' ':
csock.send('Server Responce: <> \n')
print 'srv responces: %d : <>' % c
c += 1
else:
data1 = data.upper()
csock.send('Server Responce: %s \n' % data1)
print 'srv responces: %d : <%s>' % (c, data1)
c += 1
csock.close()
except:
print 'Server socket closed !!!'