[英]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? 例如,如果我有一个变量float a = 0.5
或一个2d整数数组,等等。如何将其从客户端发送到服务器,反之亦然?
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. 例如,我尝试仅使用writer.write(a)
做同样的事情,但是writer.write()
的输入是有限的,所以我觉得我的方法不正确。
If there is a better way for me to try to be sending variables aside from using BufferedReaders&BufferedWriters, could you let me know? 如果除了使用BufferedReaders&BufferedWriters之外,还有其他更好的方法可以尝试发送变量,您能告诉我吗?
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. 在处理Java客户端/服务器通信时,如果您对两端具有完全控制权,并且不希望更改设计,则可以通过Object * Stream类使用Java序列化直接直接执行编码。
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 ) (请参见https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html和https://docs.oracle.com/javase/8/docs/api/java/io/ ObjectInputStream.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.