带有Java客户端的golang服务器

I have a big problem.... We have a project on school and work as dou. I write the go server and my partner the java client. I have a problem that if he is sending something like: "Hello World" the golang server split this into "Hello" and "World"

See Picture

The Java Code:

public class DataController {
public String recieveDataFromServer(Socket socket) throws Exception {

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while (!bufferedReader.ready()) { }
    String data = bufferedReader.readLine();
    return data;
}

public void sendDataToServer(Socket socket, String data) throws Exception
{
    PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
    printWriter.println(data);
}
}

The go Code:

func handleRequest(conn net.Conn) {
request := make([]byte, 256)

for {
    _, err := conn.Read(request)
    if err != nil {
        Error.Println(err.Error())
        return
    }               
    Info.Println("Message Received: " + string(request))
    message := []byte(time.Now().String())
    message = append(message, []byte(": ")...)
    message = append(message, request...)
    broadcast(message)
}
}

The broadcast function just do a conn.Write(msg) for all the connections.

Does anyone know that the problem is?

Edit: I found the problem. Java add after each word a . Then the go server think the message ended. We switch now to c#. its easier and work correct while writing with a bufferedWriter to a socket.

You maybe need send first the number of bytes to read and later the bytes to read with io.ReadFull function... of this way you are sure that read all the string...

ReadFull in go https://golang.org/pkg/io/https://golang.org/pkg/io/

ReadFully Java with DataInputStream : https://docs.oracle.com/javase/8/docs/api/

  • First read int with the number of bytes....

  • Later read bytes with io.ReadFull method...

NOTE : You need write the integers in bigendianess to java.

binary.Write(tx, binary.BigEndian, value)

My advice make the complex in go and read int and readFull bytes in java...

NOTE : You can only simple write bytes in both directions if you need send images or some similar...

Code to send and write bytes in Go

Code to send and write bytes in Java

I hope this help...

In this case i will suggest to use gRPC. here is the documentation

and here is gitrepo.

Use protobuf instead of JSON to define the contract of service.

So you can use this service for other clients as well which may be in any language.

and for implementing this you just need to extract your service contract and generate your contract in client respective language.

May be its little expensive in term of building but it will make your project reusable and definately you will learn something new.