Last active
June 22, 2020 07:31
-
-
Save ahmadmustafaanis/ffebbeb099b89e7ae61e0ae72b1e8689 to your computer and use it in GitHub Desktop.
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
# Socket Programming by Ahmad Mustafa Anis | |
import socket | |
class ServerSocket: | |
def __init__(self, type=socket.AF_INET, family=socket.SOCK_STREAM, port = 8080): | |
self.type = type | |
self.family = family | |
self.mySock = socket.socket(self.type, self.family) #Ipv4 and TCP Socket | |
self.mySock.bind((socket.gethostname(), port)) #Binded to local computer ip and 8080 port | |
self.mySock.listen(5) #can add upto 5 connections in a queue. | |
def accept_and_recv(self): | |
self.client, self.addr = self.mySock.accept() #accepts a new connection | |
self.msg = self.client.recv(1024) #recives 1024 bytes from client | |
self.msg = self.msg.decode('utf-8') #decodes it | |
def convert_and_send(self): | |
self.msg = self.msg.upper() #converts client msg to uppercase | |
self.client.send(bytes(self.msg,'utf-8')) #send it back to client in decoded format | |
self.client.close() #closes connection with client. | |
server = ServerSocket() | |
try: | |
server.accept_and_recv() | |
server.convert_and_send() | |
except Exception as E: | |
print(E) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment