Created
February 18, 2016 00:25
-
-
Save Ttech/cd8b2e04ff01bf1a7a4b to your computer and use it in GitHub Desktop.
Basic Python Chat Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import socket | |
import sys | |
from time import gmtime, strftime | |
from pprint import pprint | |
host = '' # server | |
port = 38002 # port | |
size = 1024 # packet size | |
s = None | |
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM): | |
af, socktype, proto, canonname, sa = res | |
try: | |
s = socket.socket(af, socktype, proto) | |
except OSError as msg: | |
s = None | |
continue | |
try: | |
s.connect(sa) | |
except OSError as msg: | |
s.close() | |
s = None | |
continue | |
break | |
nickname = "" | |
if nickname is None or nickname is "": | |
print("Please enter a username", end=": ") | |
nickname = input() | |
# if all that worked, we now have two threads we can use | |
print("Connecting") | |
s.send(bytearray(nickname,'utf-8')) | |
loop=True | |
s.send(bytearray(" \n ",'utf-8')) # to get the data flowing? but why... | |
def background(): | |
global size,loop, s | |
while loop: | |
line = s.recv(size) | |
if line.decode("utf-8") is "\n" or line.decode("utf-8") is "": | |
pass | |
else: | |
message = line.decode('utf-8') | |
print("< %s" % message) | |
def send_message(message): | |
global s, size, loop | |
time = strftime("%Y-%m-%d %H:%M:%S", gmtime()) | |
s.send(bytearray(message + "\n",'utf8')) | |
# now threading1 runs regardless of user input | |
threading1 = threading.Thread(target=background) | |
threading1.daemon = True | |
threading1.start() | |
while True: | |
user_input = input() | |
if "exit" in user_input: | |
s.close() | |
sys.exit() | |
else: | |
send_message(user_input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment