简体   繁体   中英

Java Sockets - Sending data from client to server

My objective: send a local variable from the client program to the server program.

I have the client and server connected, and I know how to send string messages from the client to the server.

Example:

private void sendToServer(Socket clientSocket) throws IOException{
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    writer.write("You have connected to the server.");
    writer.flush();
    writer.close();
}

The above code works perfectly and sends a message.

But what do I do if I want to send data/variables between a client and a server?

For example what if I had a variable float a = 0.5 , or a 2d integer array, etc. how would I send that from client to server or vice-versa?

I tried doing the same thing just using writer.write(a) instead, for example, but the inputs for writer.write() are limited, so I feel like I'm approaching it incorrectly.

If there is a better way for me to try to be sending variables aside from using BufferedReaders&BufferedWriters, could you let me know?

Thanks!

When dealing with java client/server communications, if you have full control over both ends and don't anticipate designs changing, you can directly perform encoding directly using Java serialization through the Object*Stream classes.

Example:

 ObjectOutputStream output = new ObjectOutputStream(bufferedSocketStream);

  output.writeInt(42); // Write a primitive integer
  output.writeObject("Hello World"); // Write a string as an object
  output.writeObject(myClass); // Write a class instance that you've implemented the "Serialize" interface

  output.flush();

  /* INPUT */
  ObjectInputStream inputStream = new ObjectInputStream(bis);
  int value = inputStream.readInt(); // Will receive 42
  Object value2 = inputStream.readObject(); // Will receive "Hello World"
  Object value3 = inputStream.readObject(); // Will receive your serialized class instance

(see https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html and https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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