Difference between revisions of "Python Client Server"

From UVOO Tech Wiki
Jump to navigation Jump to search
(Created page with "client.py ``` #!/usr/bin/env python3 import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.ge...")
 
 
Line 1: Line 1:
 +
server.py
 +
```
 +
#!/usr/bin/env python3
 +
 +
import socket                                       
 +
 +
# create a socket object
 +
serversocket = socket.socket(
 +
        socket.AF_INET, socket.SOCK_STREAM)
 +
 +
# get local machine name
 +
host = socket.gethostname()                         
 +
 +
port = 9999                                         
 +
 +
# bind to the port
 +
serversocket.bind((host, port))                                 
 +
 +
# queue up to 5 requests
 +
serversocket.listen(5)                                         
 +
 +
while True:
 +
  # establish a connection
 +
  clientsocket,addr = serversocket.accept()     
 +
 +
  print("Got a connection from %s" % str(addr))
 +
   
 +
  msg = 'Thank you for connecting'+ "\r\n"
 +
  clientsocket.send(msg.encode('ascii'))
 +
  clientsocket.close()
 +
```
 +
 
client.py
 
client.py
 
```
 
```
Line 21: Line 53:
 
s.close()
 
s.close()
 
print (msg.decode('ascii'))
 
print (msg.decode('ascii'))
 +
```
 +
 +
# Run server and connect with client in two terminals
 +
```
 +
server.py
 +
client.py
 
```
 
```

Latest revision as of 17:48, 4 August 2020

server.py

#!/usr/bin/env python3

import socket                                         

# create a socket object
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 9999                                           

# bind to the port
serversocket.bind((host, port))                                  

# queue up to 5 requests
serversocket.listen(5)                                           

while True:
   # establish a connection
   clientsocket,addr = serversocket.accept()      

   print("Got a connection from %s" % str(addr))

   msg = 'Thank you for connecting'+ "\r\n"
   clientsocket.send(msg.encode('ascii'))
   clientsocket.close()

client.py

#!/usr/bin/env python3

import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 9999

# connection to hostname on the port.
s.connect((host, port))                               

# Receive no more than 1024 bytes
msg = s.recv(1024)                                     

s.close()
print (msg.decode('ascii'))

Run server and connect with client in two terminals

server.py
client.py