Java Socket Programming - java

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);

Related

Java(client) and C#(Server) TCP Socket. and Server read infinite last data from client

Java(client) and C#(Server) TCP Socket. and Server read infinite last data from client(Java)
I has been search for entire day already, its weird.
I created 2 client: Java(real), C#(for testing)
like this:
Java(Real):
Socket socket = new Socket(SyncActivity.ip,SyncActivity.port);
DataOutputStream out;
out = new DataOutputStream(socket.getOutputStream());
String s = "Hello!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$";
out.write(s.getBytes(),0,s.getBytes().length);
out.flush();
s = "Yes this another data$";
out.write(s.getBytes(),0,s.getBytes().length);
out.flush();
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
Thread.currentThread().interrupt();
and
C#(for testing)
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("192.168.0.138", 11838);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
On C#(testing) side, sent one data to server, and server readed the data once and blocked to wait another data.(second data same as reading it once and blocked)I just want like this.
On Java(Real)side, sent two data to server and server reading 1st data once and read same 2nd data forever. Java side is verified sent only once.
It is full data I was received. Why? its weird.
result as:
on C#(testing)
Client request connection.
Server accept and created connection.
Server try Read (and Blocked)
Client send >> TextBox
Server received >> TextBox
Server try Read (and Blocked)
but on Java(Real):
Client request connection.
Server accept and created connection.
Server try Read (and Blocked)
Client send >>
Hello!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Server received >>
Hello!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Client send >> Yes this another data
Server try Read
Server received >> Yes this another data
Server try Read
Server received >> Yes this another data
Server try Read
Server received >> Yes this another data
Server try Read
Server received >> Yes this another data
Server try Read
Server received >> Yes this another data
Server try Read
Server received >> Yes this another data
(and forever and forever)
Server code:
TcpListener serverSocket = new TcpListener(IPAddress.Any, Convert.ToInt16(Ini.IniReadValue("About", "ServerPort", "MVS_VAN.info")));
TcpClient clientSocket = default(TcpClient);
serverSocket.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
serverSocket.Stop();
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[128000];
do
{
Socket soc = clientSocket.Client;
soc.Receive(bytesFrom);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
MessageBox.Show("", dataFromClient);
networkStream.Flush();
//networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
//string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
//dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
//tried ^ this 3 line also.
} while ((true));
clientSocket.Close();
serverSocket.Stop();
The server is ignoring the count returned by Receive(). It is therefore (a) ignoring endi of stream and (b) processing invalid data in the buffer.
Im found what is the problem after a day investigate.
but its still weird:
on Java Client:
socket.close();//<--here causing a start of server read same last data infinitly
it was not closing it properly. maybe where protocol is still close_wait state to ensure all packets is arrived to server?
.
fake resolve:
Im write my own command packets send to server like "cmd_request_close_connection", and close the connection on server side when server receive packet like this.

Get string or file in server side with socket programming

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);
}

ObjectInputStream from socket.getInputStream()

I have server
ServerSocket socketListener = new ServerSocket(Config.PORT);
...
client = socketListener.accept();
and client
sock = new Socket("127.0.0.1", Config.PORT);
I want to transfer between them some serialized data using ObjectInputStream and ObjectOutputStream.
When I try to do
ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
Nothing happens neither on the server side nor client side. Everything falls on that line. Both the client and the server is trying to get the input stream from the socket, but it does not work nor the client nor the server.
How do I solve this problem so that I can pass the serialized data between client and server?
As the javadoc says:
Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
So, since both the server and the client start by opening an InputStream, you implemented a deadlock: they both block until the other party has sent the stream header. If you start by opening an ObjectInputStream at client side, you must start by opening an ObjectOutputStream (and flushing immediately if necessary) at server-side (or vice-versa).

java - continuous data sending through Socket

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.

Why it cannot find getInputStream?

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.

Categories