How To Create a Python Socket Server

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Create the Python Socket Server

#!/bin/python

import socket

host = '10.10.10.10'
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    data = "Return data\n"
    client.send(data)
    client.close()

Create the client connection

#!/bin/python

import socket

host = '10.10.10.10'
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
while 1:
    client, address = s.accept()
    data = client.recv(size)
    print data
    if data == "\n":
       client.send("junk1\n")
       client.close()
    elif data == "junk\n":
       client.send("junk2\n")
       client.close()
    else:
       client.send("junk3\n")
       client.close()

Reference

http://ilab.cs.byu.edu/python/socket/echoserver.html
https://pymotw.com/2/socket/tcp.html

Leave a Reply

avatar
3000
  Subscribe  
Notify of