记录一下如何用两种语言简单通信,(其实也大差不差的,应该把。。。)
// C++ 服务端
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
using std::string;
void Error(string msg) {
cout << msg << " " << strerror(errno) << endl;
}
int main()
{
cout << "---服务器启动---" << endl;
int sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("0.0.0.0");
addr.sin_port = htons(26119);
if (bind(sock, (sockaddr*)&addr, sizeof(addr)) == -1) {
Error("绑定失败");
}
if (listen(sock, 255) == -1) {
Error("监听失败");
}
int client = accept(sock, 0, 0);
if (client == -1) {
Error("接收失败");
}
char* buffer = new char;
int len = recv(client, buffer, 0xff, 0);
cout << "有客户端连接,接收数据为:" << buffer << ",长度: " << len << endl;
cout << "发送数据" << endl;
char* buff = "hello this is came form C++";
send(client, buff, strlen(buffer), 0);
close(sock);
cout << "---服务端关闭---" << endl;
return 0;
}
// Java 客户端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Test {
public static void main(String[] args) {
System.out.println("---客户端启动---");
try{
Socket socket = new Socket("120.24.177.154",26119);
//使用PrintWriter和BufferedReader进行读写数据
PrintWriter pw = new PrintWriter(socket.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//发送数据
pw.println("hello, this's come from java socket");
pw.flush();
// //接收数据
String line = is.readLine();//readLine必须有结尾,比如\n换行,否则会一直读下去,触发超时
System.out.println("received from server " + line);
//关闭资源
pw.close();
is.close();
socket.close();
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("---客户端关闭---");
}
}
标签:PrintWriter,java,socket,C++,---,Java,include,服务端,客户端
From: https://www.cnblogs.com/yueyingyifeng/p/17858228.html