Reputation: 619
I am learning socket programming and python. For a school assignment, I created a server that runs, but I don't know how to terminate it. The instruction says that my server runs repeatedly until terminated by a supervisor (don't lead open sockets). Can someone give me an example or point me to the right direction? Thanks so much!
Here is a portion of my code:
import socket
import sys
import os
def main():
#HOST = ''
#PORT = 8888
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
server_socket.bind((HOST, PORT)) #bind to a address(and port)
except socket.error, msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#put the socket in listening mode
server_socket.listen(10) #maximum 10 connections
print 'TCP Server Waiting for client on port 30021'
#wait to accept a connection - blocking call
client, addr = server_socket.accept()
#display client information
print 'Connected with ' + addr[0] + ':' + str(addr[1])
try:
#keep talking with the client
while 1:
#Receiving from client
data = client.recv(1024)
if not data:
break
#DO SOMETHING HERE
except KeyboardInterrupt:
print "Exiting gracefully."
finally:
server_socket.close()
if __name__ == "__main__":
main()
Upvotes: 1
Views: 452
Reputation: 129139
If you're running it interactively (that is, you started it with e.g. python myprogram.py
or ./myprogram.py
and you have a console where you can see its output), you should be able to send it an interrupt, by pressing CTRLC. You should then see the “exiting gracefully” message and it should terminate.
If you're running it some other way, how to terminate it depends on what platform you're using. If you're on Windows, you should be able to find the python.exe
or pythonw.exe
process and press End Process in Task Manager. If you're on a POSIX system, you might be able to find the process with ps
and end it with kill -INT id
, where id
is the process ID you obtained from ps
.
Upvotes: 2