C++、python和go說話完成的簡略客戶端辦事器代碼示例。本站提示廣大學習愛好者:(C++、python和go說話完成的簡略客戶端辦事器代碼示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++、python和go說話完成的簡略客戶端辦事器代碼示例正文
任務頂用到了C/S模子,所做的也不過是給辦事器發數據,但開辟階段會碰到法式本身的回環測試,須要用到簡略的辦事端以便驗證數據發送的准確性。
寫軟件用C++,跑測試用python,這段時光也恰好看go說話,所以都要有demo。以下三組法式完成的功效雷同,這裡一路做下總結。
1、C++完成
Boost.Asio是一個跨平台的C++庫,它用古代C++辦法為收集和底層I/O法式供給了分歧的異步I/O模子。 為了跨平台,我用boost庫完成,詳細以下。
辦事端代碼:
/*
File : svr.cpp
Author : Mike
E-Mail : [email protected]
*/
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
enum {max_length = 1024};
typedef boost::shared_ptr<tcp::socket> socket_ptr;
int main()
{
boost::asio::io_service io_service;
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), atoi("12345")));
for (;;)
{
socket_ptr sock(new tcp::socket(io_service));
a.accept(*sock);
char data[max_length];
boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
data[length] = 0;
std::cout<<data<<std::endl;
sock->close();
}
return 0;
}
客戶端代碼:
/*
File : cli.cpp
Author : Mike
E-Mail : [email protected]
*/
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), "127.0.0.1","12345");
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
std::cout << "Please input: ";
char request[max_length];
std::cin.getline(request, max_length);
size_t request_length = strlen(request);
boost::asio::write(s, boost::asio::buffer(request, request_length));
return 0;
}
編譯:g++ cli.cpp -o cli -lboost_system -lboost_thread-mt
2、python完成
辦事端代碼:
'''
File : svr.py
Author : Mike
E-Mail : [email protected]
'''
import socket,os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 12345))
sock.listen(5)
while True:
connection,address = sock.accept()
buf = connection.recv(1024)
print buf
connection.close()
客戶端代碼:
'''
File : cli.py
Author : Mike
E-Mail : [email protected]
'''
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 12345))
#sock.send('Test\n')
sock.send(raw_input("Please input : "))
sock.close()
3、go說話完成
辦事端代碼:
/*
File : svr.go
Author : Mike
E-Mail : [email protected]
*/
package main
import(
"net"
"fmt"
"bufio"
)
func main() {
client,err := net.Listen("tcp","127.0.0.1:12345")
if err != nil {
fmt.Printf("Error : %s\n",err.String())
}
for {
if c, err := client.Accept(); err == nil {
defer c.Close()
line, _ := bufio.NewReader(c).ReadString('\n')
fmt.Println(line)
}
}
}
客戶端代碼:
/*
File : cli.go
Author : Mike
E-Mail : [email protected]
*/
package main
import(
"net"
"fmt"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:12345")
if err != nil {
fmt.Printf("Error : %s\n",err.String())
}
conn.Write([]byte("Just a test"))
}
運轉後果(go說話為例):
好,就這些了,願望對你有贊助。