Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python sockets

'''
a library used to create end points. 
heres a quick exemple of a client and a local TCP server:'''

#server file
import socket

soc = socket.socket(socket.AF_INET) #initializing the socket

IP = "111.111.1.111" #the ip of the server. use 'ipconfig' on cmd to check your ip address (make sure its ipv4 because its a local server)
PORT = 5050 #the port of the server. can be any port as long its not in use 

soc.bind((IP,PORT)) #binding the ip and the port of the server
soc.listen() #letting the server accept clients
client, address = soc.accept() #waiting for a user to connect and store the user in the client variable and them address to the adress variable
client.send(b'hello client!') #sending a byte string to the client.



#client file (can be created from a different pc): 

soc = socket.socket(socket.AF_INET) #initializing the socket

IP = "111.111.1.111" #the ip of the server.  
PORT = 5050 #the port of the server.

soc.connect((IP,PORT)) #connecting to the server.

print(soc.recv(1024).decode()) #receiving the byte string from the server. passing as a parameter how much bytes we want to recieve. and we printing it on the string (the .decode() is used to decode the bytes)
 
PREVIOUS NEXT
Tagged: #python #sockets
ADD COMMENT
Topic
Name
4+5 =