I need to adapt the following simple code so that to achieve the following:
the client will send requests to the server to reverse strings (taken as a command
line input) over the network using sockets.
the client and the server negotiate through a fixed negotiation port (<n_port>) of the server, a random port (<r_port>) for later use. Then, later in the transaction stage, the client connects to the server through the negotiated random port (<r_port>) for actual data transfer.
Here is the code:
#TCP Server:
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('''',12020))
serverSocket.listen(1)
print 'The server is ready to receive'
while True:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence.
encode())
connectionSocket.close()
TCP Client
from socket import *
serverName = ’servername’
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print modifiedMessage.decode()
clientSocket.close()
Will appreciate your help.
Related
So far, I have been working with Sockets. One socket for sending and receiving. I've been told that that is stupid, however I was not able to find the correct way to use socketpairs on client and server from ground up. I will give my current way, and hope someone could tell me how to do socketpairs with this. Using TCP by the way.
#client
import socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = "127.0.1.1"
port = 22222
my_socket.connect((ip, port))
#server
import socket
import multiprocessing
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_address = socket.gethostbyname(hostname)
port = 22222
s.bind((ip_address, port))
s.listen(20)
connections=[]
connection_threads=[]
while True:
clientsocket, address = s.accept()
#does this create a new socket for every incoming connection by the way?
new_client = client.Client(address, clientsocket)
connections.append(new_client)
new_process = multiprocessing.Process(target=client_butler.connect_client, args=(new_client,))
new_process.start()
connection_threads.append(new_process)
My end goal would be that the server has one socketpair for every client. I know that this is probably not good implementation as it is completely ignoring errorhandling and so on, but I will look at that in the future as all I am trying to do is me self teaching this. So the question is, how would I transform this into working with socketpairs?
Problems I have:
How do I connect the socketpair as in my client via my_socket.connect?
If I just connect both sockets individually, how do I 'reassemble' the pair in the server
Am I even doing this correctly, or is this the completely wrong approach?
Also: I checked this out, but even if I could copy the code and it would work I wouldn't know why it would work, which isn't what I want, I don't want this to work I'd also like to learn from this.
Thanks!
Referenced from Computer Networking: A Top-Down Approach, 7th Edition:
client.py:
from socket import *
serverName = "127.0.0.1"
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
sentence = input('Input lowercase sentence: ')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print('From Server: ', modifiedSentence.decode())
clientSocket.close()
server.py
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('The server is ready to receive')
while True:
connectionSocket, addr = serverSocket.accept()
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()
This is a server code by python
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))
print(" the server is ready to receive")
while 1:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
and the client code is
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input ('Input lowercase sentense:')
clientSocket.sendto(message.encode(),(serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print (modifiedMessage)
clientSocket.close()
I run the server first the output is
enter image description here
Then I run client and enter the lowercase sentence after that the client and server does't do anything else
enter image description here
please help me.
Your problem is here:
while 1:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)`
Indentation in Python is important. Your server process will never reach the third statement as it is technically positioned after the end of an infinite loop.
listenr code :
import socket
host = socket.gethostbyname(socket.gethostname())
port = int(raw_input("PORT > "))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5)
while True:
c, addr = server.accept()
buff = 2048
print addr[0]+" connected."
c.send("Connection Established")
data = c.recv(buff)
if data:
print data
client code:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = int(raw_input("PORT > "))
server.connect((host, port))
buff = 2048
data = server.recv(buff)
if data:
print data
and is it possible to receive data from client and listen on port at the same time ? how?
After accept() use thread to send/receive data to/from client and at the same time main thread can wait for next client running accept() again. It is standard method .
I'm trying to:
Connect to a server/port
Listen for x seconds
Receive user input
Send user input to server
Go back to step 2
So far, I've written the following code, but it's not working properly receiving input after the first send. Any help would be greatly appreciated.
import socket
import select
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('domain.com', 1234))
client_socket.setblocking(0)
timeout = 5
while True:
while True:
ready = select.select([client_socket], [], [], timeout)
if ready[0]:
data = client_socket.recv(4096)
print data
else:
break
data = raw_input("Enter input:")
client_socket.send(data)
You need to have separate server side code and client side code. This article has been referred.
Server binds to a port and listens for clients
server.py
import select
import socket
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port
server_address = ('localhost', 1234)
server.bind(server_address)
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
inputs = [ server ]
# Sockets to which we expect to write
outputs = [ ]
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
for s in readable:
if s is server:
# A "readable" server socket is ready to accept a connection
connection, client_address = s.accept()
connection.setblocking(0)
inputs.append(connection)
else:
data = s.recv(1024)
if data:
print "Receiving data from client"
print data
else:
inputs.remove(s)
s.close()
Client first establishes a connection with the server and then keeps on sending user input to the server.
client.py
import socket
server_address = ('domain.com', 1234)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
while True:
data = raw_input("Enter input:")
sock.send(data)
Open terminal.
Run server in background:
python server.py &
Run client after that:
python client.py
My server (listening) is as:
import os
from socket import *
host = ""
port = 1337
buf = 1024
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
print("Waiting to receive messages...")
while True:
(data, addr) = UDPSock.recvfrom(buf)
data=data.decode('ascii')
print("Received message: " + data)
if data == "exit":
break
UDPSock.close()
os._exit(0)
and my client is
import os
from socket import *
host = "MY INTERNET IP"
port = 1337
addr = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = input("Enter message to send or type 'exit': ")
data=data.encode('ascii')
UDPSock.sendto(data, addr)
if data == "exit":
break
UDPSock.close()
os._exit(0)
so I need to know, how do I transmit these messages over internet? i have all my ports open on my network yet i can not receive any messages while trying to do that. My server is listening on port 1337 and my client is transmitting to MY INTERNET IP where a server is listening on the port it is transmitting on. so how do I get this to work, what do i do wrong? thing is, it works while doing lan. it's cozy, but very pointless since i would like to transmit text over web
EDIT
Got my friend to run client side. Python just returned 4.
Nothing happened on my side.