I have this code:
ServerSocket serverSideSocket = new ServerSocket(1234);
serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));
And compiler writes me that it cannot find "getInputStream". I do not understand why. In the beginning of my code I do import java.net.*.
Calling of accept returns instance of Socket which has required method getInputStream.
The code might look like this:
ServerSocket serverSideSocket = new ServerSocket(1234);
Socket socket = serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Great tutorial how to work with sockets in java: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
This because conceptually a ServerSocket doesn't provide a direct connection object that can be used to send and receive data. A ServerSocket is a tool that you can use with the .accept() method to let it listen on the choosen port and generate a new real connection when a client tries to connect.
That's why you can't get an InputStream from a ServerSocket. Since many clients can connect to the same server, every client will make the server socket generate a new Socket (that is an opened TCP connection) that is returned from .accept() through which you can send and receive using its InputStream and OutputStream.
Related
I am designing a distributed system by creating network using sockets in java. It has different threads which are communicating simultaneously with other servers. While designing distributed system or any network application which involves simultaneous connections is it good to create connections once and then communicating using io-streams or connections should be made and closed per message?
i dont think its a good idea to make a connection each time in when client wants to send a message because you have to wait untill server accept your connection.
//Server side code.
ServerSocket listener = new ServerSocket(9090);
Socket socket = listener.accept();
//client code
Socket s = new Socket(serverAddress, 9090);
you can create a single conection and use inputStreamReader in the rest of code to listen input and output from the both sides, that approach will make your app faster than creating a connection each time.
//client code
BufferedReader input =new BufferedReader(new InputStreamReader(s.getInputStream()));
//serverCode
PrintWriter out =new PrintWriter(socket.getOutputStream(), true);
I have created two separate programs, a client and a server. I tried testing them both within eclipse and running as runnable jars on the same (Windows) machine (localhost). It worked exactly as it should.
However, when I sent clinet (and later server) to a friend of mine to test it out, it didn't work. We made sure that ports were open (even on clients side), but to no avail. It didn't work. I would just get a timeout ConnectException.
The sockets I used were 50178-50180.
I have no idea what to think of it. Any ideas what might be going wrong?
This is the socket code:
(serverside)
serverSocket = new ServerSocket(50178);
while (true)
{
clientSocket = serverSocket.accept();
streamOut = clientSocket.getOutputStream();
objectOut = new ObjectOutputStream(streamOut);
streamIn = clientSocket.getInputStream();
objectIn = new ObjectInputStream(streamIn);
(stuff)
}
(clientside)
Socket socket = new Socket(ipAddress, 50178);
OutputStream streamOut = socket.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(streamOut);
DataInputStream dataIn = new DataInputStream(socket.getInputStream());
I didn't include rest of the code since it I/O stuff (which does indeed work because it works over localhost).
EDIT:
I added requested code. I also tried it over two computer that were on the same network (witch local ip 192.168.1.*). It worked.
You may already be doing this, but I believe that a call to serverSocket.accept() must be done. This will tell the server that it needs to wait for a connection.
If you are doing that, my best answer to you would be to perform network troubleshooting. The computers must be able to see each other on the local area network in order to be able to use just the ip address. Make sure that there is not a firewall or something like that that is preventing the connection.
If you could add the code of where the client tries to connect and where the server accepts the connection, that may be helpful.
I have two projects in java application, the fist project is client side and the second project is the server side, Client side sends file or String to server via network, I use socket programming in my projects.
In client side I have many classes, I make object from each class and fill object and the object convert to string with Gson and send to server(with socket programming). In the server side I have a socket that listens to one port , my problem is in server side, I do not know which type sends to server via network for example client can send string and file via network, in the server side I do not know which type(string or file) sends to server that I can take base on that format.
Please suggest a solution for resolve my problem.
Best regards
You can use similar to my below code
ServerSocket sersock =null;
Socket sock =null;
sersock = new ServerSocket(3333);
System.out.println("Server ready to receive");
sock = sersock.accept( );
System.out.println("accepting client request");
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage;
while(true) {
if((receiveMessage = receiveRead.readLine()) != null) {
System.out.println("receiveMessage server "+receiveMessage);
}
I'm writing a Java client/server application. It should allow clients to send text data to the server. This kind of communication should be repeatable many times using the same connection.
I write it like this:
// On a server:
ServerSocket serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if (reader.ready()) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
// do something with line
}
}
// On a client:
Socket socket = new Socket(host, port);
socket.setKeepAlive(true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write("Some data from client to server");
writer.flush();
The problem is: I can't read on a server before I close OutputStream on a client. Or I can't open OutputStream on a client again, if it was already closed. How can I do continuous sending and reading of data?
You need two threads at both ends, one for reading data and other one for writing data.
The problem is: I can't read on a server before I close OutputStream on a client.
Yes you can. You just can't get to the case where readLine() returns null. It isn't the same thing.
Or I can't open OutputStream on a client again, if it was already closed.
Of course not. You have to create a new Socket.
How can I do continuous sending and receiving of data?
I don't understand the question. The code you posted doesn't attempt that.
If your goal is to send many mesages over the same socket connection, these messages will have to be delimited by an application-level protocol. In other words, you won't be able to rely on any system calls like reader.ready() or reader.readLine() == null to detect the end of the message on te server.
One way to achieve this is to begin each message with its length in characters. The server will then read exactly that number of charecters, and then stop and wait for a new message. Another is to define a special character sequence which concludes each message. The server will react to reading that particular sequence by ending the reading of the current message and returning to the "wait for new message" state. You must ensure that this sequence never appears in the message itself.
i have a txt file with students name and marks for subjects. i send this file from client to server using
Socket clientSocket = new Socket("127.0.0.1",5432);
OutputStream os = clientSocket.getOutputStream();
os.write(clientWriteArr,0,clientWriteArr.length);
and read this file at server using
ServerSocket sock = new ServerSocket(5432);
Socket serverSocket = sock.accept();
InputStream is = serverSocket.getInputStream();
is.read(serverReadArr,0,serverReadArr.length);
i am modifying the file contents upto this all is working fine.
after this i want to send back this file back to client but i am not getting file at the client and also not getting any exception
You can leave the original socket open from which you read the file, and then write the result to the same socket before closing it. This would be a standard request/response model like what is used for HTTP, and is convenient because the server does not need to know how to connect back to the client. Give us some code for more detailed advice.
You need the the "server" to open a socket connection back to the "client" to send data back. The "client" has to be listening on the port that the "server" wants to connect to.
"Client" and "server" have dual roles in this case.
What exception do you get?
Your server side code should be like:
ServerSocket serverSocket = new ServerSocket(8999);
Socket socket = serverSocket.accept();
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Here, in : you can read the data sent by client.
out: you can write data to client
Your client code should be like:
Socket socket = new Socket("localhost", 8999);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Here, in you can send data to server.
out, you can read the data sent by server.
Reading data from input stream:
while (true) {
int c = in.read();
}
when you call in.read(), it will block current thread until it reads something.
Writing data to output stream:
out.write(data);