I am trying hands on with Socket Programming.Below is my server side code and I have not listed client side code here which is similar. As soon as the thread(in the try block) is called my console o/p disappears. Not sure how to handle this.Running it on DOS of Windows 7.Although I tried to read some existing discussion but found it was not very useful. Any help appreciated. Thanks..Ravi.
Code block:
import socket
import sys
import time
import thread
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 15000)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()
Servername = raw_input('Starting the chat(enter "QUIT" to discontinue), Please enter your name: ')
def Server_outgoing():
while True:
outgoing_message_server = raw_input()
if (outgoing_message_server == 'Quit' or outgoing_message_server == 'quit' or outgoing_message_server == 'QUIT'):
print "Server has decided to abort the chat - Bye bye"
break
print "######################################################################"
print >>sys.stderr, '"%s" : Printing outgoing message from Server "%s"' % (Servername, outgoing_message_server)
print "######################################################################"
connection.sendall(outgoing_message_server)
try:
thread.start_new_thread(Server_outgoing, ())
finally:
connection.close()
Ok guys..This worked..:
thread1 = Thread(target=Server_outgoing, args=())
thread1.start()
thread1.join()
Related
I am trying to set up a server that can send each client - commands.
One command is 'lock' which locks the screen of the client.
When a client gets the word "lock" it runs this code on the client:
import ctypes
ctypes.windll.user32.LockWorkStation()
This code does lock the screen however- it ends my connection with the client..
How can I make the client stay connected but still locked?
Note: The locking is not forever! it is only once, like putting the client's computer in sleep mode until he wants to unlock the screen.
Hope I was clear enough. Thanks for helping!
Server:
import socket
def main():
sock = socket.socket()
sock.bind(('0.0.0.0', 4582))
print("Waiting for connections...")
sock.listen(1)
conn, addr = sock.accept()
print ("New connection from: ", addr)
while 1:
command = input("Enter command> ")
if command == 'shutdown':
sock.send(b'shutdown')
elif command == 'lock':
sock.send(b'lock')
else:
print ("Unknown command")
data = sock.recv(1024)
print (data)
if __name__ == '__main__':
main()
Client:
import socket
import ctypes
def main():
sock = socket.socket()
sock.connect(('127.0.0.1', 4582))
while 1:
data = sock.recv(1024)
print (data)
if data == 'lock':
sock.send(b'locking')
ctypes.windll.user32.LockWorkStation()
sock.recv(1024)
if __name__ == '__main__':
main()
I adapted the example from the Python docs to your needs.
Example for server.py:
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
print('Waiting for connection...')
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = input('Which command? ')
if data in ['lock', 'shutdown']:
conn.send(data.encode())
else:
print('Command unknown')
Example for client.py:
import ctypes
import socket
HOST = '127.0.0.1'
PORT = 4582
with socket.socket() as s:
s.connect((HOST, PORT))
while True:
data = s.recv(1024).decode()
if not data:
print('Server disconnected')
break
print('Received command:', data)
if data == 'shutdown':
print('Shutting down client...')
break
if data == 'lock':
print('Locking...')
ctypes.windll.user32.LockWorkStation()
I am new to python and I am currently working on a chat room program in Python (still in progress...). I have also made a GUI for my program. Initially, I made two py files, one for the GUI and one for the chatting function. They both worked perfectly when separated. After, I combined the two files. I faced the following two problems:
One of my threads (target = loadMsg) is used to wait for the host's msg and print it out on the screen. The problem is that it delays for one msg every time. For example, I sent a "1" to the host and the host should return a "1" immediately. But, the "1" I received didn't appear on my screen. Then I send a "2" to the host and the host should reply a "2" immediately. Then, my screen shows a "1" but the "2" is still missing until the host reply a "3" to me, after I send a "3" to the host. Where is the problem?
This is a technical problem. I was testing the stability of the chat room and I found that about 10% of my msg disappeared during the transmission and this situation occurs randomly. How can I fix such a problem?
Sorry for my poor English. I hope someone can help me with it.T_T
Here is my code for your reference:
---Client
import pygtk,gtk
import logging
from threading import *
import socket
DEBUG = 1
HOST = ''
PORT = 8018
TIMEOUT = 5
BUF_SIZE = 1024
class Base():
def reload(self):
try:
buf = self.sock.recv(BUF_SIZE)
print buf
self.addMsg(buf)
except:
pass
def reload_butt(self,widget):
try:
self.thread = Thread(target=self.reload)
self.thread.start()
except:
pass
def loadMsg(self):
try:
while True :
buf = self.sock.recv(BUF_SIZE)
print buf
self.addMsg(buf)
except:
self.sock.close()
def sendMsg(self,widget):
if DEBUG : print "Send Msg"
if self.entry.get_text() : self.sock.send(self.entry.get_text())
self.entry.set_text("")
def addMsg(self,string):
if DEBUG : print "Try to add Msg"
if self.entry.get_text() :
iter = self.buffer1.get_iter_at_offset(-1)
self.buffer1.insert(iter,("\n Username: "+string))
self.entry.set_text("")
self.adj = self.scrolled_window.get_vadjustment()
self.adj.set_value( self.adj.upper - self.adj.page_size )
if DEBUG : print "Add msg ok"
def destroy(self,widget):
if DEBUG : print "Destroy function called"
self.sock.close()
gtk.main_quit()
def __init__(self,sock):
if DEBUG : print "Initializing..."
self.sock = sock
self.win=gtk.Window()
self.win.connect("destroy",self.destroy)
self.vbox=gtk.VBox()
self.win.add(self.vbox)
self.view=gtk.TextView()
self.view.set_editable(False)
self.buffer1=self.view.get_buffer()
self.scrolled_window=gtk.ScrolledWindow()
self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
self.scrolled_window.add(self.view)
self.vbox.add(self.scrolled_window)
self.entry=gtk.Entry()
self.entry.connect("activate",self.sendMsg)
self.enter=gtk.Button("Enter")
self.enter.connect("clicked",self.sendMsg)
self.reload=gtk.Button("Reload")
self.reload.connect("clicked",self.reload_butt)
self.hbox=gtk.HBox()
self.hbox.add(self.entry)
self.hbox.pack_start(self.reload,False,False)
self.hbox.pack_start(self.enter,False,False)
self.vbox.pack_start(self.hbox,False,False)
self.win.show_all()
if DEBUG : print "Finish initializing"
def main(self):
try :
gtk.main()
except :
print "Error!!!"
def main() :
try :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print ('Connecting to '+ str(HOST) +' ' + str(PORT))
base=Base(sock)
thread1=Thread(target=base.loadMsg)
thread2=Thread(target=base.main)
thread2.start()
thread1.start()
except :
print "Err0r!!!"
sock.close()
main()
---host (an echo host)
import socket
HOST = ''
PORT = 8018
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
try :
print "Start!"
while True:
data = conn.recv(1024)
print data
reply = data # echo
if not reply : break
if reply== "!q" :
conn.close()
break
conn.send(reply)
conn.close()
except :
print "Error!!!!!"
conn.close()
I would seriously recommend to use the gio library (part of glib). Using that library, you connect functions to the socket operations such as when data is available, or when data can be written to the socket. The library will call these function when necessary, and you don't need a wait loop. Which is more CPU-friendly.
http://jcoppens.com/soft/howto/gtk/chat_socket.php contains an example of communications between a C program and Python, using gio, which might be useful to you.
This way, you can start monitoring the sockets after the GUI has started, and you do not need threads to attend the communications.
I'm a python(3) begginer and I want to do a n-players game. This players will connect to the server to play. I'm practicing with an easy example I've found, but when I run it, it throws an error "Traceback (most recent call last)" and another "OS [WinError 10048]", anyone knows why? Could you explain me how to try it out in my pc, being both client and server?.
import socket
#Server
s = socket.socket()
s.bind((socket.gethostname(), 9999))
s.listen(1)
sc, addr = s.accept()
while True:
received = sc.recv(1024)
if received == "quit":
break
print ("Received:", received)
sc.send(received)
print ("bye")
sc.close()
s.close()
#Client
s = socket.socket()
s.connect((socket.gethostname(), 9999))
while True:
message = input("> ")
s.send(message)
if message == "quit":
break
print ("bye")
s.close()
I've previously read that it can be a problem with the Firewall, but that's not my case.
Thank you for any help you can bring me!
save both files in the same directory and open 2 terminals there
run server.py first (it should just wait for a connection)
(if you already have server.py running somewhere this will result in an error, only one instance of server.py may be running on a given computer/port at a time )
then run client.py (while server.py is running in first terminal)
client.py
import socket
s = socket.socket()
s.connect((socket.gethostname(), 9999))
while True:
message = input("> ")
s.send(message)
if message == "quit":
break
print ("bye")
s.close()
server.py
import socket
#Server
s = socket.socket()
s.bind((socket.gethostname(), 9999))
s.listen(1)
sc, addr = s.accept()
while True:
received = sc.recv(1024)
if received == "quit":
break
print ("Received:", received)
sc.send(received)
print ("bye")
sc.close()
s.close()
i think your problem is in your adress binding. instead of s.bind((socket.gethostname(), 9999)), it should be s.bind((socket.gethostname(socket.gethostbyname()), 9999))
I am creating a Python Server/Client chat program (like AOL instant messenger) using sockets.
I run into a problem when I force quit the server or the client because my socketInstance.recv() method is sent a huge amount of "" blank strings. I am wondering how to run a closing method, like a deconstructor, when the cmd window is force quit so I can exit gracefully.
I've included my code, just in case (shouldn't be necessary tho):
Echo server program
import socket
import sys
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s = socket.socket() # Create a socket object
HOST = socket.gethostname() # Get local machine name
print "Socket hostname: ", HOST
s.bind((HOST, PORT))
conn = None
def check_for_messages():
print 'Check for messages...'
global conn
while 1:
try:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
print data
except socket.error:
#[Errno 10054] Client Closes
pass
print "END OF CHECK MESS"
def check_for_client():
print 'Listening...'
global conn
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
check_for_client()
check_for_messages()
Echo client program
import threading
import socket
import time
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = socket.gethostname() # The local host
s.connect((HOST, PORT))
getUserInputThread = None
getMessThread = None
receivedMessages = []
def getMessage():
print "getMessageThread running"
while 1:
data = s.recv(1024)
if not data:
print "OVERLORD: Possible server disconnect"
break
receivedMessages.append(data)
print "getMessageThread ending\n"
def getUserInput():
print "getUserInputThread running"
while 1:
message = raw_input("type: ")
s.sendall(message)
#print messages in list:
while len(receivedMessages) > 0:
print "Received Messages Length: %d" % len(receivedMessages)
print receivedMessages.pop(0)
print "getUserInputThread ending"
getUserInputThread = threading.Thread(target=getUserInput)
getUserInputThread.start()
getMessThread = threading.Thread(target=getMessage)
getMessThread.start()
Thanks,
Jordan
You could use the atexit module to perform final cleanup before terminating:
import atexit
#atexit.register
def do_cleanup():
print "doing some cleanup..."
#close sockets, put chairs on tables, etc
print "goodbye"
#loop forever, until the user hits ctrl-c
while True:
pass
Result:
C:\Users\kevin\Desktop>test.py
Traceback (most recent call last):
File "C:\Users\kevin\Desktop\test.py", line 12, in <module>
while True:
KeyboardInterrupt
doing some cleanup...
goodbye
This will work if your user force quits with a KeyboardInterrupt, but not if he closes the command window with the X button, terminates the task with task manager, unplugs the computer, etc.
I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code:
import sys, os, socket
host = ''
port = 50103
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w', 0)
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
And here is my client:
import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
file.close()
Here is my problem. I start the server and then run the client on the same machine. I enter the port and connect. Then I get the raw_input which is the '$'. If I type a command like 'ls' it just hangs on the client side. I have to exit the server for the client to receive the output of ls. By the way I am running Ubuntu Linux. Not sure if that matters.
When you makefile() on the socket and then use readlines() on it, it will continue until you reach an end of file, which in the socket case is that it closed from the other end.
Using makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and recv() on both ends.
You probably also want to have some sort of actual "protocol" so the server tells the client "HERE COMES A RESPONSE" and "THIS IS THE END OF THE RESPONSE" so that the client knows. Otherwise it gets hard to know when to stop waiting for more response. :)
Update with an example that works:
server.py:
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 50500))
print("Server started")
s.listen(1)
while True:
print "Accepting"
conn, addr = s.accept()
print 'New connection from ', addr
while True:
try:
rc = conn.recv(1024)
print "Command", rc
if not rc.strip():
continue
if rc.strip() == 'END':
print "Close"
conn.send("**END**")
conn.close()
break
else:
conn.send("This is the result of command %s\n" % rc)
except Exception:
conn.close()
sys.exit()
client.py
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50500))
while True:
cmd = raw_input('$ ')
s.send(cmd)
result = s.recv(1024)
print result
if result == "**END**":
print "Ending"
break
Well for one thing you're only connecting on the client once and on the server you're closing the socket after every read.
You should take a look at this example.
http://ilab.cs.byu.edu/python/socket/echoserver.html
You're doing quite a few things incorrectly.