I am trying to run a simple python script on the Cisco Packet Tracer for testing. The code is for opening a socket for a TCP connection with a client only to get a string, set it to uppercase and send the modified string back to the client.
The code below works well on my machine; however, when I try to run this very same code on a virtual server created on the Cisco Packet Tracer (programming interface on the server), it returns the error: NotImplementedError: socket is not yet implemented in Skulpt in file src/lib/socket.py on line 1
from socket import *
import sys
serverPort = 3125 # Defines the port this socket will be listening
# Opens the socket, AF_INET: IPv4 | SOCK_STREAM: TCP socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Assigns the serverPort to the server socket
serverSocket.bind(("", serverPort))
serverSocket.listen(1) # Listens to one connection on the "handshake socket"
print("The server is ready to serve...") # Prints the server is running
while True:
# Accepts the connection with the client
connectionSocket, clientAddress = serverSocket.accept()
# Receives the messagem from the client
message = connectionSocket.recv(2048)
# Closes the server if the message is "exit"
if message.decode() == "exit":
connectionSocket.close()
break
# Modifies the message to upper case
modifiedMessage = message.decode().upper()
# Sends the modified message to the client
connectionSocket.send(modifiedMessage.encode())
connectionSocket.close() # Closes the socket
serverSocket.close() # Closes the handshake socket
sys.exit()
I appreciate.
Related
I'm building a Client-Server connection for an assignment. The server basically runs everything and the client only receives messages from the server and responds when the server needs it to.
For some reason, I can't build a client that repeatedly listens and then responds.
I thought that I could just listen with socket.recv() and it ended up just stopping everything.
this is what I ended up with after some tweaking (for the client) :
import socket
HOST = 'localhost'
PORT = 65432
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((HOST, PORT))
conn.setblocking(False)
while True :
try :
msg_lgn = len(conn.recv(1024,socket.MSG_PEEK))
server_message = conn.recv(1024).decode()
print('Server Sent:\n' + server_message)
if server_message == 'exit':
break
except :
conn.send(input().encode())
conn.close()
I set it to non-blocking so it won't hang on the conn.recv() and move on to input in the exception, but then it just freezes on the input.
does the server close the connection every time recv() gets nothing ? why is this happening ?
I just want the client to receive messages whenever the server sends them, and when the server doesn't send, the client will send the server it's input.
would appreciate any help!
Lidor
Edit : the server file is much bigger, so i'll show the important parts.
#imported some classes for the game itself also (that i've created), but has nothing to do with the problem
import socket
import time
import threading
def startGame(conn):
#this is where the servers sends the questions and receives answer (pretty basic send and recv)
# Establish Client-Server Connection
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(3)
# Use Threading to start the game for an new player
while True:
if playerCount < 3:
(conn, addr) = s.accept()
playerCount += 1
x = threading.Thread(target=startGame, args=(conn,))
x.start()
# Close Server Socket
s.close()
In the first part of this assignment you are going to implement an echo server which receives text message from client and sends it back to the client. (That’s why we call it echo server) When the server receives the text message from client, it capitalizes the odd characters of the text message. For example, when the client sends a text message of “hello elec 4120 student”, the server should return a text message of “HeLlO ElEc 4120 StUdEnT”.
With some hints from the instructor, my server code is as follow
from socket import *
serverPort = 12000
#create TCP welcoming socket
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
#server begins listening for incoming TCP requests
serverSocket.listen(1)
print('The server is ready to receive')
while True:
#server waits on accept()
#for incoming requests, new socket created on return
connectionSocket, addr = serverSocket.accept()
#read bytes from socket (but not address as in UDP)
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
#close connection to this client (but not welcoming socket)
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()
and the client code is
from socket import *
serverPort = 12000
serverName = 'localhost'
#create TCP socket for server, remote port 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence:')
#No need to attach server name, port
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence.decode())
clientSocket.close()
and when I run the server code
'The server is ready to receive'
is shown but when I run the client part,
line 6, in <module>
clientSocket.connect((serverName,serverPort))
ConnectionRefusedError: [Errno 61] Connection refused
is shown
I'm trying to run the below program but I keep getting connection error's:
from socket import *
from codecs import decode
HOST = 'localhost'
PORT = 5000
BUFSIZE = 1024
ADDRESS = (HOST, PORT)
server = socket(AF_INET, SOCK_STREAM)
server.connect(ADDRESS)
dayAndTime = decode(server.recv(BUFSIZE), 'ascii')
print(dayAndTime)
server.close()
ERROR: ConnectionRefusedError: [Errno 61] Connection refused
Any idea what's going on?
If your book doesn't mention the other half of sockets, you need a better book.
Socket basics are easy. You have one process listen on a port, waiting for connections. Commonly we'll call this a 'server'. Another process (perhaps on the same machine, perhaps remote) attempts to connect to that port. We'll call that the client.
If no one is listening, then when the client attempts to connect they'll get your error Connection Refused.
So, set up a listening process. Below, on the left is server code; on the right is client code. Top-to-bottom is the "flow".
server = socket(AF_INET, SOCK_STREAM) # <- just like your example
server.bind(ADDRESS) # rather than 'connect', we 'bind' to the port
server.listen(1) # bind "claims" the port, so next we call listen & wait...
# Meanwhile...
# Your client process
client = socket(AF_INET, SOCK_STREAM)
client.connect(ADDRESS)
# It's only at this moment that the client reaches across the network to the server...
# On connect, the listening server wakes up, and needs to "accept" the connection
(s, remote_addr) = server.accept()
Once accepted, you can now send/recv on the s socket on the server-side, and send/recv from the client socket on the client side. Note that the server variable is not the socket to communicate on -- it's used to listen for new connections. Instead, you read/write on the socket object returned as first item of accept().
There's lots more to consider but this is at the heart of the Internet and has been pretty much unchanged since the 1980s.
Image from wikipedia entry for Berkeley Sockets:
I am creating a game in Pygame that requires a client-server part for the multiplayer.
First, I am checking if there are less than two connections. If this is the case, the client will be shown a screen that says 'waiting for connections'.
I have got the client to successfully send a '1' message to the server, which will respond with a '1' if the server is not full. Therefore, if the server does not respond with a 1, the server is full, and the client can continue.
However, I am getting this error mentioned in the title.
Server code:
import socket
import sys
import threading
from _thread import *
import time
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
ip=socket.gethostbyname(host)
port=8000
connections=[]
print('Your local ip address is',ip)
s.bind((host,port))
s.listen(2)
def threaded_client(connection):
while True:
data=connection.recv(2048) #anything we receive
if not data:
break
connection.close()
def checkconnected(connections):
noofconn=len(connections)
while True:
print('Waiting for a connection...')
connection,address=s.accept()
print(address,'has connected to server hosted at port',address[1])
connections.append(address)
data=connection.recv(1024)
received=[]
counter=0
for letter in data:
received.append(data[counter])
counter+=1
received=(chr(received[0]))
if received=='1':#handling initial connections
if len(connections)!=2:
s.sendall(b'1')
if not data:
break
start_new_thread(threaded_client,(connection,))
s.close()
The client code that calls it:
host=socket.gethostname()
ip=socket.gethostbyname(host)
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
address=address
port=8000
if address==ip:
ishost=True
else:
ishost=False
try:
s.connect((address,port))
connectionwaitingmenu()
connected=False
while connected==False:
s.sendall(b'1')
data=s.recv(1024)
received=[]
counter=0
for letter in data:
received.append(data[counter])
counter+=1
received=(chr(received[0]))
if received=='1':
connected=False
elif received!='1':
connected=True
classselection()
The error occurs on the s.sendall(b'1') line in the server code.
There are a few other problems in your code, but the cause of the error in the title is that you're using the wrong socket to send and receive data on the server side.
When a server accepts a new client (conn, addr = server.accept()) this returns a new socket, which represents the channel through which you communicate with the client. All further communication with this client happens by reading and writing on conn. You should not be calling recv() or sendall() on s, which is the server socket.
The code should look something like this:
# Assuming server is a bound/listening socket
conn, addr = server.accept()
# Send to client
conn.sendall(b'hello client')
# Receive from client
response = conn.recv(1024)
# NO
server.send(b'I am not connected')
this_wont_work = server.recv(1024)
I have I/O controller (which can turn on/off the lights) connect to the server (digitalocean running on ubuntu) using TCP/IP protocol. I/O controller acts as a client. I have python script listening connections from clients. This python script path /root/tcp_socket/server_socket.py
server_socket.py
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
import _thread
import time
import datetime
host = '0.0.0.0'
port = 8080
buf = 1024
addr = (host, port)
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversocket.bind(addr)
serversocket.listen(10)
clients = [serversocket]
def handler(clientsocket, clientaddr):
print("Accepted connection from: ", clientaddr)
while True:
data = clientsocket.recv(1024)
while True:
try:
print("Server is listening for connections\n")
clientsocket, clientaddr = serversocket.accept()
clients.append(clientsocket)
_thread.start_new_thread(handler, (clientsocket, clientaddr))
except KeyboardInterrupt:
print("Closing server socket...")
serversocket.close()
I have web site which is built on python Flask framework running on ubuntu. In my website has toggle buttons such as turn on and turn off.
Turn on and turn off toggles. path /var/www/FlaskApp/FlaskApp/
My question is how can I access from web page to connected clients which can handle by using server_socket.py.And how can I send "On" command to the I/O controller when on toggle clicked