Сервер постоянно слушает
А клиент хочет по очереди передать сообщения, не отключаясь от клиента.
Server
#!/usr/bin/env python
# coding=utf-8
import socket
class MyTCPServer( object ):
def __init__(self, adress='127.0.0.1', port='9999'):
self.addr = adress
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind( ( self.addr, self.port ) )
self.sock.listen(5)
def run(self):
while True:
client, addr = self.sock.accept()
print 'connect:%s' % addr
data = client.recv(1024)
print 'Message:%s' % data
if __name__ == '__main__':
HOST, PORT = '127.0.0.1', 9999
try:
server = MyTCPServer()
server.run()
#!/usr/bin/env python
# coding=utf-8
import socket
import sys
class ClientRCP(object):
def __init__(self, ip_address='127.0.0.1', port=9999):
self.id_addr = ip_address
self.port = int( port )
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
try:
self.sock.connect( ( self.id_addr, self.port ) )
except socket.error, er:
print 'Failed connection to:%s on port:%s' % ( self.id_addr, self.port )
self.sock.close()
sys.exit(0)
def sent_mess(self, mess):
self.sock.send( mess )
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser(usage='''\
prog: [options]
-a --address = address server
-p --port = port server
Example:
client.py -a 192.168.1.2 -p 8090
''')
parser.add_option('-a', '--address', dest='address', default='127.0.0.1',
help='Address for connect to server', metavar='ADDRESS')
parser.add_option('-p', '--port', dest='port', default='9999',
help='Port for connect to server', metavar='PORT')
( option, argv ) = parser.parse_args()
print 'Args %s, %s' % ( option, argv )
myclient = ClientRCP( option.address, option.port )
while True:
stt = raw_input('Input message:')
myclient.sent_mess(stt)