socket编程1 [Python]


服务器端: echo-server.py

[root@lvdbing socket]# cat echo-server.py
#!/usr/bin/env python
from socket import *
myHost = ''
myPort = 12345
socketobj = socket(AF_INET,SOCK_STREAM)
socketobj.bind((myHost,myPort))
socketobj.listen(5)
while True:
        connection, address = socketobj.accept()
        print 'Server connected by', address
        while True:
                data = connection.recv(1024)
                if not data: break
                connection.send('Echo=>' + data)
        connection.close()

客户端: echo-client.py
[root@lvdbing socket]# cat echo-client.py
#!/usr/bin/env python
import sys
from socket import *
serverHost = 'localhost'
serverPort = 12345
message = ['Welcome to lvDbing blog']
if len(sys.argv) > 1:
        serverHost = sys.argv[1]
if len(sys.argv) > 2:
        message = sys.argv[2:]
socketobj = socket(AF_INET, SOCK_STREAM)
socketobj.connect((serverHost, serverPort))
for line in message:
        socketobj.send(line)
        data = socketobj.recv(1024)
        print 'Client received:', repr(data)
socketobj.close()