0

In python socket programming, e.g. chat, main aim is to keep receiving messages from others, while receiving if he presses any key, program should take the input and send that message instead of printing received messages. After finished sending, it should print received messages. How to do this without explicitly asking user to type message?

Thanks.

kanchan
  • 13
  • 1
  • 4

1 Answers1

1

If I understand your question correctly, you're gonna want to use some form of event system. Treat entering text and receiving messages as events.

http://en.wikipedia.org/wiki/Event_(computing)

Event system in Python

Since something like this is a real-time program, your program is going to be running in a loop. Throughout the loop, events are put onto a queue, and at the beginning of each loop they are handled in the order they were triggered.

Since you're working with networking, maybe a dash of threading would be useful. Due to the Global Interpreter Lock, Python can't really use multithreading for performance boosts, but it's still useful for doing I/O in the back. This way, while your chat client (to use your example) is trying to get the message the other person has sent, the rest of the program doesn't freeze. This is especially beneficial for slow internet connections.

Community
  • 1
  • 1
JesseTG
  • 2,025
  • 1
  • 24
  • 48
  • thanks for your reply, Is there any built-in function to check whether a key has been pressed or not? – kanchan Mar 09 '13 at 21:03
  • but I wonder how to listen to the keyboard while doing other stuff?? I have some experience in python multithreading. Can u please elaborate how to listen to keyboard? – kanchan Mar 09 '13 at 21:18
  • That depends on the library you want to go with. I rather like Pygame's event system. http://pygame.org/docs/ref/event.html Every time you poll for events, you can see if any of them are of type `pygame.KEYDOWN`, and if so act upon that, and you can get the key with `the_event_object.key`. Make your own events with `pygame.Event()`, and fire them by passing them to `pygame.event.post`. Events themselves don't typically have methods, instead you should make something that keeps an eye out for the presence of certain types of events (called listeners), then acts upon them if necessary. – JesseTG Mar 09 '13 at 21:29