我编写了一个客户机-服务器程序,它执行以下操作:
1.客户端将文件发送到服务器
2.服务器读取文件并进行一些更改,然后向客户端发回一条消息
3.客户应阅读信息
在第三步我得到这个错误
客户端程序
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private static final String serverIP = "127.0.0.1";
private static final int serverPort = 3248;
private static final String fileToSend = "content.txt";
public static void main(String args[]) throws InterruptedException, UnknownHostException, IOException {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
DataOutputStream outToServer = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
clientSocket = new Socket( serverIP , serverPort );
outToServer = new DataOutputStream(clientSocket.getOutputStream());
is=clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
if (outToServer != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToServer.write(mybytearray, 0, mybytearray.length);
outToServer.flush();
outToServer.close();
// File sent, exit the main method
} catch (IOException ex) {
// Do exception handling
}
}
if(is!=null){
try {
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
System.out.println("in ");
for(byte b:baos.toByteArray()){
System.out.print(b);
}
return;
} catch (IOException ex) {
// Do exception handling
System.out.println(""+ex.getMessage());
}
finally{
clientSocket.close();
is.close();
}
}
}
}
服务器程序
import java.io.*;
import java.net.*;
class TCPServer {
private static final String fileOutput = "output.txt";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
FileInputStream fromClient=null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
fromClient=(FileInputStream)connectionSocket.getInputStream();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//System.out.println(""+fromClient);
if(fromClient !=null){
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = fromClient.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = fromClient.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
connectionSocket.close();
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
暂无答案!
目前还没有任何答案,快来回答吧!