本文介绍了C ++客户端无法与Java服务器通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的客户端在Java能够与服务器在Java通信。 C ++客户端不使用以java编写的服务器。有人可以帮我解决这个问题。我提供了所有3的代码(Java服务器,Java客户端,C + +客户端)



C ++客户端:

  #include< iostream> 
#include< conio.h>
#include< winsock2.h>
#include< string>



int main(int argc,char * argv [])
{
WSAData版本; //我们需要检查版本。
WORD mkword = MAKEWORD(2,2);
int what = WSAStartup(mkword,& version);
if(what!= 0){
std :: cout<<不支持此版本 - \\\
< }
else {
std :: cout<<Good - Everything fine!\\\
<< std :: endl;
}

SOCKET u_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock == INVALID_SOCKET)
std :: cout<<创建套接字fail \ n;

else
std :: cout<<可以创建socket\\\
;

//套接字地址信息
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(192.168.45.88);
addr.sin_port = htons(15000);
std :: cout<<成功提供了地址<< std :: endl;
/ * ==========寻址完成========== * /

//现在我们连接
int conn = connect(u_sock,(SOCKADDR *)& addr,sizeof(addr));
std :: cout<<conn value:<< conn<< std :: endl;
if(conn == SOCKET_ERROR){
std :: cout<<错误 - 当连接<<<< WSAGetLastError()<< std :: endl;
closesocket(u_sock);
WSACleanup();
}
std :: cout<<<成功连接到服务器<< std :: endl;

//向远程主机发送一些消息
char * mymsg =Hello Server ...你好吗?
char vect [512] = {0};

int smsg = send(u_sock,mymsg,sizeof(mymsg),0);
if(smsg == SOCKET_ERROR){
std :: cout<<Error:< WSACleanup();
}

int get = recv(u_sock,vect,512,0);
if(get == SOCKET_ERROR){
std :: cout<<在接收时出错:< }
std :: cout<< vect<< std :: endl;
closesocket(u_sock);

getch();

return 0;

}

Java服务器:

  import java.net。*; 

import java.io. *;



public class EchoServer {

public static void main(String [] args)throws IOException {



/ * if(args.length!= 1){

System.err.println(用法:java EchoServer< port number&

System.exit(1);

} * /

int portNumber = 15000;

try(

ServerSocket serverSocket = new ServerSocket(portNumber);

Socket clientSocket = serverSocket.accept();

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

){

String inputLine;

while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
out.println(inputLine);

}

} catch(IOException e){

System.out.println(尝试在端口上侦听时捕获异常

+ portNumber +或侦听连接);

System.out.println(e.getMessage());

}

}

}


b $ b

Java客户端:

  import java.io. *; 
import java.net。*;

public class EchoClient {
public static void main(String [] args)throws IOException {

if(args.length!= 0){
System.err.println(
Usage:java EchoClient< host name>< port number>);
System.exit(1);
}

String hostName =192.168.45.88;
int portNumber = 15000;

try(
Socket echoSocket = new Socket(hostName,portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(),true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader in))
){
String userInput;
while((userInput = stdIn.readLine())!= null){
out.println(userInput);
System.out.println(echo:+ in.readLine());
}
} catch(UnknownHostException e){
System.err.println(不知道主机+ hostName);
System.exit(1);
} catch(IOException e){
System.err.println(无法获取I / O连接到+
hostName);
System.exit(1);
}
}
}


解决方案>

好的。我会付出一些努力。种种清爽的事情做。 ^^
我修改了你的代码,所以使用消息长度模式。 c客户端向服务器发送消息,java客户端对其进行解码,并将其发送回客户端。所以你有两个方向的编码和运行。请尝试理解,代码中发生了什么,否则你会再次遇到问题。 ByteOrder的东西在java端完成,所以你可以用你封闭的C服务器。



C客户端:

  int main(int argc,char * argv [])
{

WSAData版本; //我们需要检查的版本。
WORD mkword = MAKEWORD(2,2);
int what = WSAStartup(mkword,& version);
if(what!= 0){
std :: cout<<不支持此版本 - \\\
< }
else {
std :: cout<<Good - Everything fine!\\\
<< std :: endl;
}

SOCKET u_sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock == INVALID_SOCKET)
std :: cout<<创建套接字fail \ n;

else
std :: cout<<可以创建socket\\\
;

//套接字地址信息
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(127.0.0.1);
addr.sin_port = htons(15000);
std :: cout<<成功提供了地址<< std :: endl;
/ * ==========寻址完成========== * /

//现在我们连接
int conn = connect(u_sock,(SOCKADDR *)& addr,sizeof(addr));
std :: cout<<conn value:<< conn<< std :: endl;
if(conn == SOCKET_ERROR){
std :: cout<<错误 - 当连接<<<< WSAGetLastError()<< std :: endl;
closesocket(u_sock);
WSACleanup();
}
std :: cout<<<成功连接到服务器<< std :: endl;

//向远程主机发送一些消息
char * mymsg =Hello Server ...你好吗?
int length = strlen(mymsg);
//将整数转换为char并发送它
int smsg = send(u_sock,reinterpret_cast< char *>(& length),sizeof(int),0);
//发送实际消息
smsg = send(u_sock,mymsg,strlen(mymsg),0);


int newlength;
//正确接收4个字节的长度。如果没有收到正确的长度,请重复。
int get = 0;
while((get + = recv(u_sock,(reinterpret_cast< char *>(& newlength))+ get,4,0)) std :: cout< ;Length:< newlength<< std :: endl;
//使用newlength + 1创建新的数组,所以我们有一个零终止的字符串。
char * newMsg = new char [newlength + 1];
memset(newMsg,0,newlength + 1);
get = 0;
//接收字符串。如果没有收到正确的长度,请重复。
while((get + = recv(u_sock,newMsg + get,newlength,0))< newlength){}
std :: cout<<Message:< newMsg<< std :: endl;

closesocket(u_sock);


int i;
std :: cin>>一世;
return 0;
}

Java服务器:

  public static void main(String [] args){
//为事件调度线程调度作业:
//创建并显示此应用程序的GUI 。#
int portNumber = 15000;

try(

ServerSocket serverSocket = new ServerSocket(portNumber);

Socket clientSocket = serverSocket.accept();


OutputStream os = clientSocket.getOutputStream();
PrintWriter out = new PrintWriter(os,true);
// BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream ));
InputStream is = clientSocket.getInputStream();

){

// RECV
//为长整型创建ByteBuffer
ByteBuffer bLength = ByteBuffer.allocate(4);
// C通常是Little_Endian
bLength.order(ByteOrder.LITTLE_ENDIAN);
//读取4个字节
is.read(bLength.array(),0,4);
//转换长度
int length = bLength.getInt();
System.out.println(Length:+ length);


//为消息分配ByteBuffer
ByteBuffer bMessage = ByteBuffer.allocate(length);
bMessage.order(ByteOrder.LITTLE_ENDIAN);
is.read(bMessage.array(),0,length);
//将消息转换为字符串
String msg = new String(bMessage.array());
System.out.println(msg);


// SEND
//创建ByteBuffer,长度为
ByteBuffer bLengthNew = ByteBuffer.allocate(4);
bLengthNew.order(ByteOrder.LITTLE_ENDIAN);
bLengthNew.putInt(msg.length());

//将长度bytebuffer写入输出流
os.write(bLengthNew.array());

//将消息写入输出流。 (不要使用println)
out.print(msg);
//冲洗它。 (它自动在一个\\\
上刷新,但我们不想要。
out.flush();

} catch(IOException e){

System.out.println(当试图监听端口

+ portNumber +或侦听连接时捕获到异常);

System.out.println e.getMessage());

}



}


I have written the client in Java is able to communicate with the server in Java. C++ Client is not working with server written in java. Can someone please help me to resolve this problem. I have provided the code of all the 3(Java server, Java Client, C++ Client)

C++ Client:

#include <iostream>
#include <conio.h>
#include <winsock2.h>
#include<string>



int main(int argc, char* argv[])
{
   WSAData version;        //We need to check the version.
    WORD mkword=MAKEWORD(2,2);
    int what=WSAStartup(mkword,&version);
    if(what!=0){
    std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl;
    }
    else{
    std::cout<<"Good - Everything fine!\n"<<std::endl;
    }

    SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(u_sock==INVALID_SOCKET)
    std::cout<<"Creating socket fail\n";

    else
    std::cout<<"It was okay to create the socket\n";

    //Socket address information
    sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr("192.168.45.88");
    addr.sin_port=htons(15000);
    std::cout<<"Successfully provided the address"<<std::endl;
    /*==========Addressing finished==========*/

    //Now we connect
    int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
    std::cout<<"conn value:"<<conn<<std::endl;
    if(conn==SOCKET_ERROR){
    std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
    closesocket(u_sock);
    WSACleanup();
    }
     std::cout<<"Successfully connected to server"<<std::endl;

     //Send some message to remote host
    char* mymsg="Hello Server...How are you?";
    char vect[512]={0};

    int smsg=send(u_sock,mymsg,sizeof(mymsg),0);
    if(smsg==SOCKET_ERROR){
    std::cout<<"Error: "<<WSAGetLastError()<<std::endl;
    WSACleanup();
    }

    int get=recv(u_sock,vect,512,0);
    if(get==SOCKET_ERROR){
    std::cout<<"Error in Receiving: "<<WSAGetLastError()<<std::endl;
    }
    std::cout<<vect<<std::endl;
    closesocket(u_sock);

    getch();

    return 0;

}

Java Server:

import java.net.*;

import java.io.*;



public class EchoServer {

    public static void main(String[] args) throws IOException {



       /* if (args.length != 1) {

        System.err.println("Usage: java EchoServer <port number>");

        System.exit(1);

    }*/

    int portNumber = 15000;

    try (

        ServerSocket serverSocket =  new ServerSocket(portNumber);

        Socket clientSocket = serverSocket.accept();

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

    ) {

        String inputLine;

        while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        out.println(inputLine);

        }

    } catch (IOException e) {

        System.out.println("Exception caught when trying to listen on port "

        + portNumber + " or listening for a connection");

        System.out.println(e.getMessage());

    }

    }

}

Java Client:

import java.io.*;
import java.net.*;

public class EchoClient {
    public static void main(String[] args) throws IOException {

    if (args.length != 0) {
        System.err.println(
        "Usage: java EchoClient <host name> <port number>");
        System.exit(1);
    }

    String hostName = "192.168.45.88";
    int portNumber = 15000;

    try (
        Socket echoSocket = new Socket(hostName, portNumber);
        PrintWriter out =
        new PrintWriter(echoSocket.getOutputStream(), true);
        BufferedReader in =
        new BufferedReader(
            new InputStreamReader(echoSocket.getInputStream()));
        BufferedReader stdIn =
        new BufferedReader(
            new InputStreamReader(System.in))
    ) {
        String userInput;
        while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println("echo: " + in.readLine());
        }
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + hostName);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to " +
        hostName);
        System.exit(1);
    }
    }
}
解决方案

Alright. I'll put some effort into this. Kind of a refreshing thing to do. ^^I modified your code, so the message length pattern is used. The c client sends a message to the server, the java client decodes it and sends it back to the client. So you have both direction of encoding up and running. Please try to understand, what is happening in the code, otherwise you will run into problems again. The ByteOrder Stuff is completly done on the java side, so you can fiddle around with your closed C server.

C Client:

int main(int argc, char* argv[])
{

    WSAData version;        //We need to check the version.
    WORD mkword=MAKEWORD(2,2);
    int what=WSAStartup(mkword,&version);
    if(what!=0){
    std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl;
    }
    else{
    std::cout<<"Good - Everything fine!\n"<<std::endl;
    }

    SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(u_sock==INVALID_SOCKET)
    std::cout<<"Creating socket fail\n";

    else
    std::cout<<"It was okay to create the socket\n";

    //Socket address information
    sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    addr.sin_port=htons(15000);
    std::cout<<"Successfully provided the address"<<std::endl;
    /*==========Addressing finished==========*/

    //Now we connect
    int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
    std::cout<<"conn value:"<<conn<<std::endl;
    if(conn==SOCKET_ERROR){
    std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
    closesocket(u_sock);
    WSACleanup();
    }
     std::cout<<"Successfully connected to server"<<std::endl;

     //Send some message to remote host
    char* mymsg="Hello Server...How are you?";
    int length = strlen(mymsg);
    //Cast the integer to char and send it
    int smsg=send(u_sock,reinterpret_cast<char*>(&length), sizeof(int),0);
    //Send the actual message
    smsg=send(u_sock,mymsg,strlen(mymsg),0);


    int newlength;
    //Receive exactly 4 bytes for the length. If not the right length is received, repeat.
    int get = 0;
    while((get+=recv(u_sock,(reinterpret_cast<char*>(&newlength))+get,4,0)) < 4) {}
    std::cout<<"Length: " << newlength << std::endl;
    //Create new char array with newlength + 1 so we have a zero terminated string.
    char* newMsg = new char[newlength+1];
    memset(newMsg,0,newlength+1);
    get = 0;
    //Receive the string. If not the right length is received, repeat.
    while((get+=recv(u_sock,newMsg+get,newlength,0)) < newlength) {}
    std::cout<<"Message: " << newMsg << std::endl;

    closesocket(u_sock);


    int i;
    std::cin >> i;
    return 0;
}

Java Server:

public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.#
        int portNumber = 15000;

        try (

            ServerSocket serverSocket =  new ServerSocket(portNumber);

            Socket clientSocket = serverSocket.accept();


            OutputStream os = clientSocket.getOutputStream();
            PrintWriter out = new PrintWriter(os, true);
            //BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            InputStream is = clientSocket.getInputStream();

        ) {

            //RECV
            //Create ByteBuffer for length integer
            ByteBuffer bLength = ByteBuffer.allocate(4);
            //C is usually Little_Endian
            bLength.order(ByteOrder.LITTLE_ENDIAN);
            //Read 4 bytes
            is.read(bLength.array(), 0, 4);
            //Convert the length
            int length = bLength.getInt();
            System.out.println("Length: "+length);


            //Allocate ByteBuffer for message
            ByteBuffer bMessage = ByteBuffer.allocate(length);
            bMessage.order(ByteOrder.LITTLE_ENDIAN);
            is.read(bMessage.array(), 0, length);
            //Convert the message to string
            String msg = new String( bMessage.array() );
            System.out.println(msg);


            //SEND
            //Create ByteBuffer with length
            ByteBuffer bLengthNew = ByteBuffer.allocate(4);
            bLengthNew.order(ByteOrder.LITTLE_ENDIAN);
            bLengthNew.putInt(msg.length());

            //Write the length bytebuffer to the outputstream
            os.write(bLengthNew.array());

            //Write the message to the outputstream. (Don't use println)
            out.print(msg);
            //Flush it. (It automatically gets flushed on a \n, but we dont want that.
            out.flush();

        } catch (IOException e) {

            System.out.println("Exception caught when trying to listen on port "

            + portNumber + " or listening for a connection");

            System.out.println(e.getMessage());

        }



    }

这篇关于C ++客户端无法与Java服务器通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 04:11