Вы находитесь на странице: 1из 4

Client

Here's simple code to send and receive data by TCP in Python:

Toggle line numbers


1 #!/usr/bin/env python
2
3 import socket
4
5
6 TCP_IP = '127.0.0.1'
7 TCP_PORT = 5005
8 BUFFER_SIZE = 1024
9 MESSAGE = "Hello, World!"
10
11 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 s.connect((TCP_IP, TCP_PORT))
13 s.send(MESSAGE)
14 data = s.recv(BUFFER_SIZE)
15 s.close()
16
17 print "received data:", data

Server

Here's simple code to serve TCP in Python:

Toggle line numbers


1 #!/usr/bin/env python
2
3 import socket
4
5
6 TCP_IP = '127.0.0.1'
7 TCP_PORT = 5005
8 BUFFER_SIZE = 20 # Normally 1024, but we want fast response
9
10 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

1
11 s.bind((TCP_IP, TCP_PORT))
12 s.listen(1)
13
14 conn, addr = s.accept()
15 print 'Connection address:', addr
16 while 1:
17 data = conn.recv(BUFFER_SIZE)
18 if not data: break
19 print "received data:", data
20 conn.send(data) # echo
21 conn.close()

import
socket

if __name__ == "__main__":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 9000))
data = "some data"
sock.sendall(data)
result = sock.recv(1024)
print result
sock.close()

server.py
import multiprocessing

import socket

def handle(connection, address):


import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("process-%r" % (address,))
try:

2
logger.debug("Connected %r at %r", connection, address)
while True:
data = connection.recv(1024)
if data == "":
logger.debug("Socket closed remotely")
break
logger.debug("Received data %r", data)
connection.sendall(data)
logger.debug("Sent data")
except:
logger.exception("Problem handling request")
finally:
logger.debug("Closing socket")
connection.close()

class Server(object):
def __init__(self, hostname, port):
import logging
self.logger = logging.getLogger("server")
self.hostname = hostname
self.port = port

def start(self):
self.logger.debug("listening")
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind((self.hostname, self.port))
self.socket.listen(1)

while True:
conn, address = self.socket.accept()
self.logger.debug("Got connection")
process = multiprocessing.Process(target=handle, args=(conn,
address))
process.daemon = True
process.start()
self.logger.debug("Started process %r", process)

if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG)
server = Server("0.0.0.0", 9000)
try:
logging.info("Listening")
server.start()
except:
logging.exception("Unexpected exception")
finally:
logging.info("Shutting down")
for process in multiprocessing.active_children():
logging.info("Shutting down process %r", process)
process.terminate()
process.join()
logging.info("All done")

3
python "hello.py"

python -m py_compile fileA.py fileB.py fileC.py ...

Or make your script executable by adding #!/usr/bin/env python to the top of the
script, making the file executable with chmod +x hello.py and then running:
./hello.py

Вам также может понравиться