简体   繁体   English

从c ++服务器向java客户端发送消息

[英]send messages from c++ server to java client

I am new in c++ and socket programming. 我是c ++和socket编程的新手。 I managed to create a server using c++ in a unix machine and I connected that server to a java client running in a different windows machine. 我设法在unix机器中使用c ++创建服务器,并将该服务器连接到在不同的Windows机器上运行的java客户端。 I also managed to send messages from client to server succefully. 我还设法成功地从客户端向服务器发送消息。 What I havent managed yet is to send messages from server to client. 我还没有管理的是从服务器向客户端发送消息。 I suppose it is that I am new to c++ but i didnt find something very helpfull on the internet. 我想这是我是c ++的新手,但我没有在互联网上找到非常有用的东西。 I only found c++ client to server communication code and not server to client. 我只发现c ++客户端到服务器通信代码而不是服务器到客户端。 Can somebody give some guidance?? 有人可以给一些指导吗?

Thnx in advance for your time and your help... Thnx提前为您的时间和您的帮助......

C++ server code C ++服务器代码

int main( int argc, const char** argv )
{


    /* SOCKET VARIABLES */
    int sock;
    struct sockaddr_in server;
    int mysock;
    char buff[1024];
    int rval;


    /*CREATE SOCKET*/
    sock =socket(AF_INET, SOCK_STREAM, 0);

    if (sock<0) 
    {
        perror("*FAILED TO CREATE SOCKET*");
        exit(1);
    }

    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(5000);

    /*CALL BIND*/
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
    {
        perror("BIND FAILED");
        exit(1);
    }


    /*LISTEN*/
    listen(sock, 5);


    /*ACCEPT*/
    do{

        mysock= accept(sock, (struct sockaddr *) 0, 0);

        if (mysock==-1) 
        {

            perror ("ACCEPT FAILED");
        }
        else
        {
            memset(buff, 0, sizeof(buff));

            if ((rval=recv(mysock, buff, sizeof(buff), 0)) < 0) 
                perror("READING STREAM MESSAGE ERROR");
            else if(rval==0)
                printf("Ending connection");
           else
                printf("MSG: %s\n", buff);

           printf("GOT THE MESSAGE (rval = %d)\n", rval);

            }

    }while (1) ;
    return 0; 

Java client code Java客户端代码

public class SOK_1_CLIENT {




    public void run() throws Exception
    {
        String adrress="172.16.151.237"; //localhost -- samemachine
        Socket SOCK =new Socket (adrress,5000);
        PrintStream PS =new PrintStream(SOCK.getOutputStream());
        PS.println("HELLO TO SERVER FROM CLIENT");

        InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
        BufferedReader BR = new BufferedReader(IR);

        String MESSAGE =BR.readLine();
        System.out.println(MESSAGE + "java");
    }


}

In C sockets are two-way communisation file descriptors. 在C套接字中是双向通信文件描述符。 You can write to them using send(2) . 您可以使用send(2)写入它们。 Check man 2 send . 检查man 2 send

 char * buffer;
 size_t length, sent;

 while (length && (sent = send(mysock, buffer, length, 0)) > 0) {
      length -= send;
 }
 if (sent < 0) 
     perror("send");

Please note that unlike with java's BufferedWriter in C send will not guarantee to send the entire buffer in one go. 请注意,与C语言中的BufferedWriter不同, send不能保证一次性发送整个缓冲区。 Thus the while loop. 因此while循环。 If you want buffered socket IO then you can use fdopen to create a stdio stream, but this is not recommended if you wish to be able to pass flags and intercept socket errors. 如果您需要缓冲套接字IO,则可以使用fdopen创建stdio流,但如果您希望能够传递标记并拦截套接字错误,则不建议这样做。

Ok I see that you have managed to receive messsage in C++ server and send from java client. 好的,我看到你已经设法在C ++服务器上收到消息并从java客户端发送。 See "receiving from socket" in java and "sending from socket" in C++.Use them in the above code and remember when server is sending, at the very time java client should be expecting data from server. 请参阅java中的“从socket接收”和C ++中的“从socket发送”。在上面的代码中使用它们并记住服务器发送的时间,此时java客户端应该期待来自服务器的数据。 That will solve your problem. 这将解决您的问题。

If you want to make the server-client like chat application, you have two possibilities: 如果您想使服务器客户端像聊天应用程序一样,您有两种可能:

  • Use "select" 使用“选择”
    • Use "threads" 使用“线程”

google the keywords highlighted as per your requirement and language used. 谷歌根据您的要求和使用的语言突出显示的关键字。

see this for sockets in C++ and this for java sockets 看到这个在C ++插座, 对Java插座

Use send() with the last parameter (flags) set to 0. 使用send() ,最后一个参数(flags)设置为0。

If you're on Windows then you may also need to initialise and cleanup Winsock - check this . 如果你在Windows上,那么你可能还需要初始化和清理Winsock - 检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM