java与c++socket通信问题,

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java与c++socket通信问题,相关的知识,希望对你有一定的参考价值。

server = new ServerSocket(1234);
System.out.println("等待连接");
Socket sk = server.accept();
System.out.println(sk.getInetAddress().getHostName()+"连上了");
DataInputStream input=new DataInputStream(sk.getInputStream());//得到socket流
byte[] buffer=new byte[10000];
input.read(buffer);//处理接收到的保温,传换成字符串
/*
* c++传过来的中文,默认使用gbk,需要转化,gb2312
* */
String str=new String(buffer,"GB2312").trim();
System.out.println(str);
//回复客户端
DataOutputStream out = new DataOutputStream(sk.getOutputStream());
String back="yes";
//String gbkback = new String(back.getBytes( "GBK"));
out.writeChars(back);

java客户端可以就收到c++传过来的字符串,但是我回复客户端时,c++客户端获取不到信息:如下

cout << "输入想要发送给服务器的消息内容并按回车发送:" << endl;
char *toSendtxt="客户端发送请求:1(yes) or 0(no) ?";
//cin>>toSendtxt;
if(send(connectSocket, toSendtxt, strlen(toSendtxt) + 1, 0)!=SOCKET_ERROR)

cout<<"向服务器发送的消息已经成功发送现在等待接受服务器发来的消息......"<<endl;

//客户端接收数据
int numrcv;
char buffer[MAXBUFLEN];
//int buffer1;
numrcv = recv(connectSocket,buffer,MAXBUFLEN,0);

cout<<"服务器发来的消息内容是:"<<buffer<<endl;

调试的结果是buffer是“”

请高手解答

参考技术A 用byte数组发送和接收数据,char*的不行 参考技术B 接收等待了吗,是不是一下就timeout了。。。。。。。。。追问

客户端怎么设置接收等待啊,可以展示一下相关代码吗

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

csdn在线学习课程,课程咨询答疑和新课信息:QQ交流群:422901085进行课程讨论

android跨进程通信实战视频课程(加群获取优惠)

unix socket前面几节课已经讲过了,但都是基于linux下面的c程序,那么在android中往往经常会遇到c代码的native程序要与
apk的java程序进行socket通信,本节课我们来实现一下:
直接上代码:
native端作为服务端:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/epoll.h>
#include <sys/un.h>
int main()
{
    char *socket_path = "server-socket";
    struct sockaddr_un serun, cliun;
    socklen_t cliun_len;
    int listenfd, connfd, size;
    char buf[80];
    int i, n;
    if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        perror("socket error");
        exit(1);
    }
    //unlink(socket_path);
    memset(&serun, 0, sizeof(serun));
    serun.sun_family = AF_UNIX;
    serun.sun_path[0] = 0;
    strcpy(serun.sun_path+1,socket_path);
    socklen_t addrlen_ = sizeof(serun.sun_family) + strlen(socket_path) + 1;
    int ret = bind(listenfd, (struct sockaddr*)&serun,addrlen_);
    if(ret == -1)
    {
        perror("bind");
        exit(0);
    }
    // 3. 监听
    ret = listen(listenfd, 20);
    if(ret == -1)
    {
        perror("listen");
        exit(0);
    }

   
    while(1)
    {
	printf("wait connect...\\n");
	socklen_t l =   sizeof(struct sockaddr_un);
        int connfd = accept(listenfd, (struct sockaddr *)&cliun, &l);
        if(connfd == -1)
        {
            perror("accept");
            exit(-1);
        }
        printf("a new client connected! ");
    
        int count = read(connfd, buf, sizeof(buf));
        if(count == 0)//客户端关闭了连接
        {
            printf("客户端关闭了连接。。。。\\n");
          
        }
        else
        {
            if(count == -1)
            {
                perror("read");
                exit(-1);
            }
            else
            {
                //正常通信
                printf("client say: %s\\n" ,buf);
		write(connfd,"received ok",sizeof("received ok"));
            }
        }
    }
    close(listenfd);
    return 0;
}

apk端的java代码作为客户端:
只展示核心部分:

  private void sendMessage() {
        try {
            lsocket = new LocalSocket();
            LocalSocketAddress address = new LocalSocketAddress("server-socket", LocalSocketAddress.Namespace.ABSTRACT);
            lsocket.connect(address);
            String result;
            Log.i("test","rootclient send cmd to rootServer cmd = " + sendCmdText.getText().toString());
            br = new BufferedWriter(new OutputStreamWriter(lsocket.getOutputStream()));
            br.write(sendCmdText.getText().toString());
            br.newLine();
            br.flush();
//            br.close();

            Log.d("test", "========发送成功========");
            InputStream inputStream = lsocket.getInputStream();
            BufferedReader buffer = null;
            buffer = new BufferedReader(new InputStreamReader(inputStream));
            String tmpStr = null;
            while(inputStream.available() == 0) {
                try {
                //    Log.d("lsm", "========sleep======== inputStream.available() = " +inputStream.available());
                    Thread.sleep(1);
                }catch (Exception e) {

                }
            }
            byte[] buf = new byte[inputStream.available() -1];
            inputStream.read(buf,0,inputStream.available() -1) ;
            String str =new String(buf);
            Log.d("test", "========接受成功======== inputStream.available() = " +inputStream.available() + "read str  = " +str);
            final String str1 = str;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    receiveText.setText(str1);
                }
            });

            buffer.close();

            lsocket.close();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("test","rootclient rootServer 发送失败",e);
        }
    }

ps:完整代码课程中会进行提供和讲解

以上是关于java与c++socket通信问题,的主要内容,如果未能解决你的问题,请参考以下文章

JAVA服务器与客户端的socket通信问题

Android Socket学习java与native_socket通信

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

Android Framework实战开发-socket跨进程通信之native程序与apk java通信

使用Socket简单模拟C/S消息传递——Java(31)