Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from _thread import *
- import socket
- import sys
- import threading
- class Server(object):
- def __init__(self, ip, port):
- self.ip = ip
- self.port = port
- self.srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.srv_sock.bind((ip, port))
- self.srv_sock.listen(1)
- print("Chat server listening on {}:{}".format(self.ip, self.port))
- def sender_thread(self, cli_sock):
- print("we are in the thread boi")
- def receiver_thread(self, cli_sock):
- partial_msg = ""
- while True:
- chunks = cli_sock.recv(2048)
- print(chunks)
- chunks = chunks.decode().splitlines(keepends=True)
- print(chunks)
- for chunk in chunks:
- if partial_msg:
- print('Client is sending {}{}'.format(partial_msg, chunk))
- partial_msg = ""
- elif "\n" in chunk:
- print("Client is sending: {}".format(chunk))
- else:
- partial_msg = chunk
- def listen(self):
- while True:
- cli_sock, cli_addr = self.srv_sock.accept()
- print("New connection from {}...".format(cli_addr))
- start_new_thread(Server.sender_thread, (self, cli_sock))
- start_new_thread(Server.receiver_thread, (self, cli_sock))
- s = Server("127.0.0.1", 42042)
- s.listen()
- #client
- import socket
- import sys
- import time
- def start():
- cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- cli_sock.connect(("127.0.0.1", 42042))
- while True:
- cli_sock.sendall("i like memes".encode('ascii'))
- time.sleep(3)
- cli_sock.sendall("very much\ni like memes better than networking\n".encode('ascii'))
- response = cli_sock.recv(2)
- print(response.decode('ascii'))
- cli_sock.close()
- start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement