Python Socket Programming (Python3)

# server.py

from socket import *

# all available on host
myHost = ''

myPort = 50007
# create a TCP/IP socket object
sockobj = socket(AF_INET, SOCK_STREAM)
# Bind socket object to host/port
sockobj.bind((myHost, myPort))
# Allow 5 pending connects

sockobj.listen(5)

 

# always listen until process is killed
while True:
     # wait for next client connect
    connection, address = sockobj.accept()
     # simple print out the client's address
    print('Server connected by', address)
    while True:
          # read data from client socket
        data = connection.recv(1024)
        if not data: break
         # send a reply line back to client

        connection.send(b'Echo=>'+data)
    connection.close


 

# Client.py

 

import sys
from socket import *

serverHost = 'localhost'
serverPort = 50007
# Default message to server
message = [b'Hello network world']

if len(sys.argv) > 1:
     # First system argv indicate to the server host address
    serverHost = sys.argv[1]
      # second system argv replace the message to server
    if len(sys.argv) > 2:
        message = (x.encode() for x in sys.argv[2:])

# Create a TCP/IP socket object
sockobj = socket(AF_INET, SOCK_STREAM)
# Connect to host/server
sockobj.connect((serverHost, serverPort))
for line in message:
     # send message to server
    sockobj.send(line)
     # receive response data from server

    data = sockobj.recv(1024)
    print('Client received:', data)

 

sockobj.close()

 

 


 

Start Server:
tracy@tracyDesktop:~/Documents/python$ python3 testServer.py

Start Client:
tracy@tracyDesktop:~/Documents/python$ python3 testClient.py


 

Response of server:

tracy@tracyDesktop:~/Documents/python$ python3 testWeb.py
Server connected by ('127.0.0.1', 46030)
Tracy: b'Hello network world'
// Server still waiting for next client's connect

Response of client:

tracy@tracyDesktop:~/Documents/python$ python3 testWebClient.py
Client received: b'Echo=>Hello network world'



Start Client again
tracy@tracyDesktop:~/Documents/python$ python3 testClient.py "localhost" "I'M Tracy"


Response of server:

 

tracy@tracyDesktop:~/Documents/python$ python3 testWeb.py
Server connected by ('127.0.0.1', 46030)
Tracy: b'Hello network world'
Server connected by ('127.0.0.1', 46044)
Tracy: b"I'M Tracy"

// Server still waiting for next client's connect

Response of client:

tracy@tracyDesktop:~/Documents/python$ python3 testWebClient.py "localhost" "I'M Tracy"
Client received: b"Echo=>I'M Tracy"



lbysdc 發表在 痞客邦 留言(0) 人氣()