Advertisement
Guest User

Untitled

a guest
Oct 11th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. from _thread import *
  2. import socket
  3. import sys
  4. import threading
  5.  
  6. class Server(object):
  7.  
  8.     def __init__(self, ip, port):
  9.         self.ip = ip
  10.         self.port = port
  11.         self.srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12.         self.srv_sock.bind((ip, port))
  13.         self.srv_sock.listen(1)
  14.         print("Chat server listening on {}:{}".format(self.ip, self.port))
  15.  
  16.     def sender_thread(self, cli_sock):
  17.         print("we are in the thread boi")
  18.  
  19.     def receiver_thread(self, cli_sock):
  20.         partial_msg = ""
  21.  
  22.         while True:
  23.             chunks = cli_sock.recv(2048)
  24.             print(chunks)
  25.             chunks = chunks.decode().splitlines(keepends=True)
  26.             print(chunks)
  27.  
  28.             for chunk in chunks:
  29.                 if partial_msg:
  30.                     print('Client is sending {}{}'.format(partial_msg, chunk))
  31.                     partial_msg = ""
  32.                 elif "\n" in chunk:
  33.                     print("Client is sending: {}".format(chunk))
  34.                 else:
  35.                     partial_msg = chunk
  36.  
  37.     def listen(self):
  38.         while True:
  39.             cli_sock, cli_addr = self.srv_sock.accept()
  40.             print("New connection from {}...".format(cli_addr))
  41.  
  42.             start_new_thread(Server.sender_thread, (self, cli_sock))
  43.             start_new_thread(Server.receiver_thread, (self, cli_sock))
  44.  
  45. s = Server("127.0.0.1", 42042)
  46. s.listen()
  47.  
  48.  
  49. #client
  50.  
  51. import socket
  52. import sys
  53. import time
  54.  
  55. def start():
  56.     cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  57.     cli_sock.connect(("127.0.0.1", 42042))
  58.     while True:
  59.         cli_sock.sendall("i like memes".encode('ascii'))
  60.         time.sleep(3)
  61.         cli_sock.sendall("very much\ni like memes better than networking\n".encode('ascii'))
  62.         response = cli_sock.recv(2)
  63.         print(response.decode('ascii'))
  64.     cli_sock.close()
  65.  
  66. start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement