Python Socket编程
目的: 客户端发送两个整数,让服务器给我们做加法,然后再用Json格式传给客户端
UDP编程
UDPClient.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #coding:utf8 from socket import * import json serverName = '127.0.0.1' serverPort = 12000 clentSocket = socket(AF_INET,SOCK_DGRAM) message1 = raw_input("InputNumber1> ") message2 = raw_input("InputNumber2> ") d = { "message1" : message1, "message2" : message2 } data = json.dumps(d) clentSocket.sendto(data,(serverName,serverPort)) modifidMessage, serverAddress = clentSocket.recvfrom(2048) mes = json.loads(modifidMessage) print int(mes['sum']) clentSocket.close()
|
UDPServer.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import json from socket import * serverPort = 12000 serverSocket = socket(AF_INET,SOCK_DGRAM) serverSocket.bind(('127.0.0.1',serverPort)) print "The server is ready to receive" while True: message, clientAddress = serverSocket.recvfrom(2048) dic = json.loads(message) print dic num1 = int(dic["message1"]) num2 = int(dic["message2"]) sum = num1 + num2 data = { "sum" : sum } d = json.dumps(data) print d serverSocket.sendto(d, clientAddress)
|
TCP编程
TCPClient.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| # coding:utf8 from socket import * import json serverName = '127.0.0.1' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName,serverPort)) #创建与服务器的连接 也就是三处握手 number1 = raw_input('Input Number1:') number2 = raw_input('Input Number2:') d = { 'num1' : number1, 'num2' : number2 } jsonStr = json.dumps(d) clientSocket.send(jsonStr) serverData = clientSocket.recv(1024) print 'From Server: ', serverData data = json.loads(serverData) print int(data['sum']) clientSocket.close()
|
TCPServer.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from socket import * import json serverPort = 12000 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('127.0.0.1', serverPort)) serverSocket.listen(1) print 'The server is ready to receive' while True: connectionSocket, address = serverSocket.accept() sentence = connectionSocket.recv(1024) jsonData = json.loads(sentence) print jsonData num1 = int(jsonData['num1']) num2 = int(jsonData['num2']) sum = num1 + num2 dic = { 'sum' : sum } clientData = json.dumps(dic) connectionSocket.send(clientData) connectionSocket.close()
|