Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, How to Send data over TCP

Tags:

python

tcp

server

I need to create a simple server that listens for TCP connections. If it receives text on<EOF> or off<EOF> then it sends (echo) back success. The receiving part is working, but now i need it to send back success.

Code:

# import threading
import SocketServer

class TCPHandler(SocketServer.BaseRequestHandler): 

   def handle(self):
      self.msg = self.request.recv(1024).strip()
      if self.msg == "on<EOF>":
         print "Turning On..."
         #ECHO "SUCCESS<EOF>"        <----- I need the server to echo back "success"
      if self.msg == "off<EOF>":
         print "Turning Off..."
         #ECHO "SUCCESS<EOF>"        <----- I need the server to echo back "success"


      if __name__ == "__main__": 
         host, port = '192.168.1.100', 1100

  # Create server, bind to local host and port 
  server = SocketServer.TCPServer((host,port),TCPHandler)

  print "server is starting on ", host, port

  # start server
  server.serve_forever()
like image 891
Ingmar05 Avatar asked Jan 07 '16 11:01

Ingmar05


People also ask

How do you transfer data to TCP ports?

The TCP Open Connection node opens a connection to the server at the port and address you specify. The address must match the IP address of the server, and the port you specify on the client must match the port you specify on the server. TCP Write nodes write data to the specified port and send commands to the server.

Which method receives TCP message in Python?

s.listen() This method sets up and start TCP listener.


2 Answers

Well i did it a day before following a very good tutorial, cant find the link but here is the code

client.py

import socket

host = socket.gethostname()
port = 12345                   # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))

For server

echo_server.py

import socket

host = ''        # Symbolic name meaning all available interfaces
port = 12345     # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))

print host , port
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:

    try:
        data = conn.recv(1024)

        if not data: break

        print "Client Says: "+data
        conn.sendall("Server Says:hi")

    except socket.error:
        print "Error Occured."
        break

conn.close()
like image 130
AbdulMueed Avatar answered Sep 25 '22 02:09

AbdulMueed


A better approach from the python 3 docs would be:

Server

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

Client

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

Hope it helps. Arturo

like image 21
Arturo Avatar answered Sep 22 '22 02:09

Arturo