我编写了以下代码,用于使用套接字从客户端向服务器发送文本文件。我是JAVA和Socket Programming的新手。我觉得我有套接字概念,但Java Streams很混乱。 任何有关以下代码的帮助都会非常有用。 请用推理提及错误和解决方案。
数据似乎发送得很好。但是在另一端却没有收到。
服务器代码:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(3000);
while(true)
{
Socket convSocket = serverSocket.accept();
System.out.println("connection accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(convSocket.getInputStream()));
FileWriter fileOut = new FileWriter("/Users/aakashmalhotra/a.txt");
int c;
while( (c = in.read()) != -1){
fileOut.write(c);
}
System.out.println("Transfer Done");
}
}
}
客户代码:
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] argv) throws Exception {
Socket clientSocket = new Socket("localhost", 3000); // create a socket
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader fileIn = new BufferedReader(new FileReader("/Users/aakashmalhotra/s.txt"));
int c;
while ((c = fileIn.read()) != -1) {
out.write(c);
}
}
}
答案 0 :(得分:2)
你需要.flush()或.close()客户端的out writer。
答案 1 :(得分:0)
总是需要关闭IO对象,尤其是流。这是因为OS针对这些类型的操作进行了优化,并且它决定何时应该在管道上发送数据。关闭资源可确保发送剩余的数据。服务器端示例:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(3000);
while (true) {
Socket convSocket = serverSocket.accept();
System.out.println("connection accepted");
try (BufferedReader in = new BufferedReader(new InputStreamReader(convSocket.getInputStream()))) {
try (FileWriter fileOut = new FileWriter("/Users/aakashmalhotra/a.txt")) {
int c;
while ((c = in.read()) != -1) {
fileOut.write(c);
}
System.out.println("Transfer Done");
}
}
}
}
}
重要的是要注意try-with-resource语句的使用,它确保无论应用程序的结果如何都将关闭流。这可以保证您的流始终处于关闭状态,并且不会泄漏任何资源。