0
내 클라이언트는 일반적으로 서버로 이미지를 보낼 수 있지만 텍스트 파일의 경우 이미지는 비어있게됩니다. 어떤 아이디어가 내가 뭘 잘못하고 있니? 나는이 일을 여러 날 동안 지금하려고 노력했기 때문에 정말로 도움을 감사 할 것입니다. 감사. 여기 소켓을 통해 이미지를 보낼 수 있지만 텍스트 파일은 보낼 수 없습니다.
class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
및
클라이언트 코드 :public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.newLine();
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
1. 안녕하세요. 소켓 물건에 아주 새롭습니다. 어떻게 만들어 졌는지 말해 주실 수 있습니까? 2. 얼마나 나쁜 실수입니까? –
@RohitMalish 1. 더 많은 데이터를 읽을 예정이라면 스트림을 닫지 않아야합니다. 2. 예기치 않은 동작이 발생할 수 있습니다. Java 소켓에 대한 초보 자습서를 따르는 것이 좋습니다. – pingw33n