[Top-Down Approach]My First C/S Program [Python]

时间:2023-03-09 16:58:16
[Top-Down Approach]My First C/S Program [Python]

These days I was learning from Computer Networking --A Top-Down Approach by Kurose Ross.
I modified the C/S model socket program in Python in Chapter 2.
Here is the program's source code.


#!/usr/bin/python2.7
# UDP - Client

from socket import *

serverName = '192.168.1.105'
serverPort = 12000

clientSocket = socket(AF_INET, SOCK_DGRAM)

while 1:
    message = raw_input('my reply:')
    clientSocket.sendto(message, (serverName, serverPort))
    modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
    print 'his reply: ' + modifiedMessage

clientSocket.close()

#!/usr/bin/python2.7
# UDP - Server

from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))

print 'The server is ready to receive'

while 1:
    message, clientAddress = serverSocket.recvfrom(2048)
    print message + str(clientAddress)
    mymsg = raw_input("my reply:")
    serverSocket.sendto(mymsg, clientAddress)

#!/usr/bin/python2.7

# TCP - Client

from socket import *

serverName = '192.168.1.105'
serverPort = 12000

clientSocket = socket(AF_INET, SOCK_STREAM)
while True:
    clientSocket.connect((serverName, serverPort))
    sentence = raw_input('input sentence: ')
    clientSocket.send(sentence)
    hisReply = clientSocket.recv(1024)
    print 'From Server:', hisReply
    clientSocket.close()

#!/usr/bin/python2.7

# TCP - Server

from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(3)
print 'The server is ready to receive'
while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024)
    print sentence + str(addr)
    myreply = raw_input('input sentence:')
    connectionSocket.send(myreply)
    connectionSocket.close()

Bingo!