简体   繁体   中英

Reading/Writing with Java Sockets

I have established a TCP connection with a server using

String hostName = ...;
int portNumber = ...;
SocketAddress addr = new InetSocketAddress(hostName, portNumber);
Socket clientSocket = new Socket();
clientSocket.connect(addr, 100);

but now I want to send a message to that server.
How do I do that using InputStreams ?

Retrieve the input stream and output stream from a Socket with getInputStream and getOutputStream . From then, you need to use the output stream (not the input stream) to send a message to the server:

Socket clientSocket = new Socket();
clientSocket.connect(addr, 100);
InputStream istream = clientSocket.getInputStream();
OutputStream ostream = clientSocket.getOutputStream();
 ... // write the message to ostream
 ... // read the server's reply from istream (if applicable)

You may want to decorate these streams into other types to facilitate your job as well, as InputStream and OutputStream are very primitive in terms of operations. For instance, if you want to write a text message, you can use PrintWriter

PrintWriter writer = new PrintWriter(ostream);
writer.print("My number: ");
writer.println(5);
writer.print("My name: ");
writer.println("John Doe");
writer.println("Done");
writer.flush();

There are different ways of achieving this. Most of the communication done with the Sockets is through their In/OutputStreams. Simple way of sending a message to the socket would be:

OutputStream output = clientSocket.getOutputStream();
output.write(Charset.getDefaultCharset().encode("Hello, world!"));

The Charset.getDefaultCharset().encode(String) is for converting a String into a byte array, as is it not possible to send any other data than bytes over a socket easily (look up "serialization")

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