How to interact with a remote server using Python Sockets

I am trying to connect to a server using python sockets. I can establish a connection and get response data. However, I want the socket connection to be interactive on the client side.

For example, if I use netcat to connect to the server, the communication is interactive:

nc aa.bb.cc.dd 1234

Server greets you
I can enter the input here
Server responds to my input

However, when I make a connection using python sockets, all I get is a greeting from the server, and the program terminates.

Here is the python code I'm using:

#! /usr/bin/python

import os
import sys
import socket

host = "aa.bb.cc.dd"
port = 1234

remote_ip = socket.gethostbyname(host)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((remote_ip, port))
print s.recv(1024)

I want to modify the above python program so that I can send inputs to the Server as well.

Thank.

+4
source share
2 answers

Usually you do

input_data = input("Enter something: ")
s.send(bytes(input_data,'utf-8'))
0

while, , .

while True:
    print(str(s.receive(1024)))
    toSend = input()
    s.send(bytes(toSend, "utf-8"))
0

All Articles