Java - Read from socket? [closed]
SO I just tried to read text from a socket, and I did the following:
i开发者_C百科mport java.io.*;
import java.net.*;
public class apples{
public static void main(String args[]) throws IOException{
Socket client = null;
PrintWriter output = null;
BufferedReader in = null;
try {
client = new Socket("127.0.0.1", 2235);
output = new PrintWriter(client.getOutputStream(), false);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while (true) {
System.out.println("Line: " + client.getOutputStream());
}
}
catch (IOException e) {
System.out.println(e);
}
output.close();
in.close();
client.close();
}
}
This prints out weird numbers and stuff like:
java.net.SocketOutputStream@316f673e
I'm not really sure of all the Java functions and things, so how would I make the output print out as text?
look at:
while (true) {
System.out.println("Line: " + client.getOutputStream());
}
getOutputSteam() returns an object that represents a stream. you can use this object to send data through the stream. here's an example:
BufferedOutputStream out = new BufferedOutputStream(this._socket.getOutputStream());
out.write("hello");
out.flush();
this will send the message "hello" through the socket
to read the data, you will use the inputstream instead
let me just point out - this is a client that you are creating. You also need to create a server. Use java's ServerSocket class for creating a server
EDIT: you want to write a client/server application in java. you need to implement 2 processes: a client and a server. the server will listen on some port (using ServerSocket). the client will connect to that port, and send a message.
first object you need to understand is ServerSocket. Server code:
ServerSocket s = new ServerSocket(61616); // this will open port 61616 for listening
Socket incomingSocket = s.accept(); // this will accept new connections
s.accept method is blocking - it waits for incoming connections, and goes to the next line only after a connection has been accepted. it creates a Socket object. for this socket object you will set up an input stream and output stream (to send/receive data).
on the client:
Socket s = new Socket(serverIp, serverPort);
this will open a socket to the server. ip in your case will be "127.0.0.1" or "localhost" (local machine), and port will be 61616.
you will again, set up input/output stream, to send/receive messages
if you are connecting to a server that already exists, you only need to implement the client of course
you can find many examples online
You aren't reading anything with this code:
while (true) {
System.out.println("Line: " + client.getOutputStream());
}
should be:
String line;
while ((line = in.readLine()) != null) {
System.out.println("Line: " + line);
}
精彩评论