简体   繁体   中英

Java Socket Programming

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM