网络编程基于TCP的Socket实现客户端与服务端的文件发送
客户端步骤
//指定的是所要连接的服务器的ip和端口。//创建文件对象//输出流//输出//刷出//读取响应//读入//关闭服务端步骤
//建立服务器端套接字//阻塞式监听//创建文件对象//输入流//读写文件//刷出//输出流 给响应//刷出//关闭客户端
import java.io.*; import java.net.Socket; /** * //指定的是所要连接的服务器的ip和端口。 * //创建文件对象 * //输出流 * //输出 * //刷出 * //读取响应 * //读入 * //关闭 */ public class Client { public static void main(String[] args) throws IOException { System.out.println("----------Client-----"); //指定的是所要连接的服务器的ip和端口。 Socket client = new Socket("localhost", 9898); //创建文件对象 File file = new File("a.txt"); InputStream is = new FileInputStream(file); //输出流 OutputStream os = client.getOutputStream(); //输出 int len; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1) { os.write(bytes, 0, len); } //刷出 os.flush(); //读取响应 client.shutdownOutput(); // InputStream is1 = client.getInputStream(); DataInputStream in = new DataInputStream(new BufferedInputStream(client.getInputStream())); //读入 String result = in.readUTF(); System.out.println(result); //关闭 in.close(); os.close(); is.close(); client.close(); } }服务端
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * //建立服务器端套接字 * //阻塞式监听 * //创建文件对象 * //输入流 * //读写文件 * //刷出 * //输出流 给响应 * //刷出 * //关闭 */ public class Server { public static void main(String[] args) throws IOException { System.out.println("-------Server------"); //建立服务器端套接字 ServerSocket server = new ServerSocket(9898); //阻塞式监听 Socket client = server.accept(); //创建文件对象 File file = new File("copya.txt"); OutputStream os = new FileOutputStream(file); //输入流 InputStream is = client.getInputStream(); //读写文件 int len; byte[] bytes = new byte[1024]; while ((len=is.read(bytes))!=-1){ os.write(bytes,0,len); } //刷出 os.flush(); //输出流 给响应 DataOutputStream os1= new DataOutputStream(new BufferedOutputStream(client.getOutputStream())); os1.writeUTF("成功"); //刷出 os1.flush(); //关闭 os1.close(); is.close(); os.close(); client.close(); } }