客户端
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.IOException;import java.io.OutputStreamWriter;import java.net.InetAddress;import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException;/** * * @author WangShuang * */public class ClientDemo { public static void main(String[] args) throws SocketException { Socket socket = null; BufferedReader br =null; try { InetAddress byName = InetAddress.getByName("192.168.1.102"); //创建客户端socket服务,指定目的主机和端口 socket = new Socket(byName,9999); //为了发送数据,应该获取socket流中的输出流,将数据写到该流中,通过网络发送给服务端 BufferedWriter bwsocket = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); //将硬盘中的文件读取到流中 br = new BufferedReader(new FileReader("c:\\文件上传.txt")); String readLine = null; while((readLine=br.readLine())!=null){ bwsocket.write(readLine); bwsocket.newLine(); bwsocket.flush(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { br.close(); //关闭客户端资源 socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
}
服务端
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class ServiceDemo { public static void main(String[] args) { //创建服务端socket服务 ServerSocket serverSocket=null; Socket socket =null; BufferedWriter bw =null; try { serverSocket = new ServerSocket(9999); //获取客户端socket对象 socket = serverSocket.accept(); BufferedReader brsocket = new BufferedReader(new InputStreamReader(socket.getInputStream())); bw = new BufferedWriter(new FileWriter("d:\\文件上传.txt")); String readLine=null; while ((readLine=brsocket.readLine())!=null) { bw.write(readLine); } } catch (IOException e) { e.printStackTrace(); }finally { try { bw.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }}