SO I just tried to read text from a socket, and I did the following:
import 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:
getOutputSteam() returns an object that represents a stream. you can use this object to send data through the stream. here’s an example:
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:
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:
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