import java.io.*;
import java.net.*;public class FileServer implements Runnable
{
private ServerSocket server;
public FileServer(int port)
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
Socket socket = server.accept();
File file = new File("d:\\2.bmp");
FileOutputStream fileOut = new FileOutputStream(file);
InputStream socketIn = socket.getInputStream();
OutputStream socketOut = socket.getOutputStream();
DataInputStream dataIn = new DataInputStream(socketIn);
PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(socketOut));
try
{
boolean flag=true;
byte[] bytes = new byte[1024];
while ((dataIn.read(bytes)) != -1)
{
if(flag)
{
socket.setSoTimeout(100);
flag=false;
}
fileOut.write(bytes);
}
}
catch (Exception e)
{
/*
* 请注意这里,如果上面的Exception e改为SocketException e就会报错
* 这是为什么?
*/
if(e instanceof SocketException)
{
}
}
fileOut.close();
writerOut.println("OK");
writerOut.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Thread(new FileServer(9999)).start();
}
}import java.io.*;
import java.net.*;public class FileClient implements Runnable
{
private Socket socket;
public FileClient(String ip, int port)
{
try
{
socket = new Socket(ip, port);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
InputStream socketIn = socket.getInputStream();
File file = new File("d:\\1.bmp");
FileInputStream fileIn = new FileInputStream(file);
OutputStream socketOut = socket.getOutputStream();
BufferedReader readerIn = new BufferedReader(new InputStreamReader(socketIn));
DataOutputStream dataOut = new DataOutputStream(socketOut); byte[] bytes = new byte[1024];
while ((fileIn.read(bytes)) != -1)
{
dataOut.write(bytes);
}
//dataOut.close();
String str = readerIn.readLine();
System.out.println(str);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Thread(new FileClient("localhost", 9999)).start();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货