I wrote a simple code for a chat client and chat server (a separate code for the client and one for the server). My server currently executes with the command line
python chatserve.py <port number>
Just found out that class requirement is that the program starts with the following command line:
./chatclient <portnumber>
How do I convert? I would greatly appreciate any tips/help. Thank you!
(To clarify any confusion, the execution of my chat client also needs a ./chatclient
in its command line, but since that part of the code was written in C, I was able to figure out how to get it to execute with specific command lines. I'm not as familiar with Python unfortunately.)
Here is the code:
#!/bin/python
from socket import *
import sys
#initiate chat with client
def chat(connectionsocket, clientname, username):
to_send = ""
while 1: # continue chat until break
# get characters from the user
received = connectionsocket.recv(501)[0:-1]
# if we received nothing, print close message and break
if received == "":
print "Closed connection. Wait for new connection..."
break
# print client username and message
print "{}> {}".format(clientname, received)
# get server input and send to client
to_send = ""
while len(to_send) == 0 or len(to_send) > 500:
to_send = raw_input("{}> ".format(username))
# special "\quit" message
if to_send == "\quit":
print "Closed connection. Wait for new connection..."
break
connectionsocket.send(to_send)
#initiate handshake with client
def handshake(connectionsocket, username):
# get the client username
clientname = connectionsocket.recv(1024)
# send server username to the client
connectionsocket.send(username)
return clientname
#execution
if __name__ == "__main__":
# If wrong number of arguments, print error message and exit
if len(sys.argv) != 2:
print "Error: no port number input"
exit(1)
# get port number and create TCP socket
serverport = sys.argv[1]
serversocket = socket(AF_INET, SOCK_STREAM)
# bind socket to port
serversocket.bind(('', int(serverport)))
# listen on port for incoming messages
serversocket.listen(1)
# get username
username = ""
while len(username) == 0 or len(username) > 10:
username = raw_input("Enter username (10 characters or less): ")
print "Receiving incoming messages..."
# continue receiving incoming messages until close
while 1:
# create new socket for incoming connection
connectionsocket, address = serversocket.accept()
# print connection message
print "Receiving connection on address {}".format(address)
# initiate handshake and chat with incoming connection
chat(connectionsocket, handshake(connectionsocket, username), username)
# close connection
connectionsocket.close()