Reference
http://www.giantflyingsaucer.com/blog/?p=4684
Here is how to use socket module
This script listens TCP 8080 port.
I am using SO_REUSEPORT options which has been implemented in kernel 3.9, so multiple processes can bind 8080 port at the same time.
# cat server.py
#!/usr/bin/env python
import os
import socket
import sys
# after TCP three way handshake, the server send data to clients
def send_data():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(('0.0.0.0', 8080))
s.listen(1)
conn, addr = s.accept()
data = str(os.getpid()) + '\n'
# data = 'hello'
conn.send(data)
conn.close()
# aftere TCP three way handhsake, the server recieve data from clients and then send clients that data
def recieve_send_data():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
s.bind(('0.0.0.0', 8080))
s.listen(1)
conn, addr = s.accept()
data = conn.recv(1024)
conn.send(data)
conn.close()
if __name__ == '__main__':
argvs = sys.argv
argc = len(argvs)
if argc != 2:
print "python server.py send or python server.py recv_send"
elif argvs[1] == 'send':
while True:
send_data()
elif argvs[1] == 'recv_send':
while True:
recieve_send_data()
|
After TCP 3 way handshake, the server send data to clients
# ./server.py send
|
After TCP 3 way handshake, the server receive data from clients and then send clients that data.
# ./server.py recv_send
|
you can run multiple scripts, because this script supports SO_REUSEPORT.
You need to use kernels which support SO_REUSEPORT.
# ./server.py send &
[1] 14053
# ./server.py send &
[2] 14054
# ./server.py send &
[3] 14055
# nc 127.0.0.1 8080
14053
# nc 127.0.0.1 8080
14055
# nc 127.0.0.1 8080
14054
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.