简体   繁体   English

Java套接字编程

[英]Java Socket Programming

i have a txt file with students name and marks for subjects. 我有一个txt文件,其中包含学生姓名和科目标记。 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. 这将是一个标准的请求/响应模型,就像HTTP所使用的那样,并且很方便,因为服务器不需要知道如何连接回客户端。 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. 在这里, in :您可以读取客户端发送的数据。 out : you can write data to client out :您可以将数据写入客户端

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. 在这里, in你可以将数据发送到服务器。 out , you can read the data sent by server. out ,您可以读取服务器发送的数据。

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. 当您调用in.read() ,它将阻塞当前线程,直到读取某些内容为止。

Writing data to output stream: 将数据写入输出流:

out.write(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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