Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find symbol method getOutputStream()

Tags:

java

Hello there when I try and use these two lines of code in my connections method in my program it gives me the error "cannot find symbol method getOutputStream()" I have no idea what I am doing wrong, heres the code

socket = new ServerSocket(6000);
socket.accept();

ObjectInputStream inputStream;
ObjectOutputStream outputStream;

outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());

Is there a command I am trying to use that doesn't exist?

like image 915
Mark Magill Avatar asked Oct 28 '25 06:10

Mark Magill


2 Answers

Simple: ServerSocket doesn't have that method. It makes no sense to write to or read from a simply "listening" socket - you need to use the streams associated with an accepted socket.

You should be using:

ServerSocket serverSocket = new ServerSocket(6000);
Socket socket = serverSocket.accept();

ObjectOutputStream outputStream =
    new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

Note how this is actually using the return value of ServerSocket.accept(), which is a Socket - and Socket does have those methods.

As a meta-comment, you said you had "no idea" what you were doing wrong: the compiler told you exactly what you were doing wrong - trying to call a getOutputStream method on ServerSocket. Your immediate first port of call after seeing that compiler error should have been the Javadoc for ServerSocket - which would have allowed you to confirm that it really didn't exist.

like image 133
Jon Skeet Avatar answered Oct 30 '25 20:10

Jon Skeet


ServerSocket's don't provide streams. Instead, they provide child Socket's once connections are made, and from those Socket's, you'll get your streams. So you need to assign a Socket s2 = to your socket.accept(), and use the streams from there.

like image 39
ziesemer Avatar answered Oct 30 '25 20:10

ziesemer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!