不多bb.
package c_20_1_5;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;public class TestSocket {public static void main(String[] args) {// Socket 与 ServerSocket// TCP 协议下的有连接, 安全传输协议。可用于任何大型文件的传输, 缺点是速度慢。//server();client();}public static void client() { Socket s = null;FileInputStream fis = null;try {System.out.println("客户端开启, 正在访问服务器...");// 发送到的地方s = new Socket(InetAddress.getByName("127.0.0.1"), 10086);// 网络输出流OutputStream out = s.getOutputStream();fis = new FileInputStream("晴天-周杰伦.mp3");byte[] b = new byte[1024*8];System.out.println("正在发送...");int len;while ((len = fis.read(b)) != -1) {// 分段发送到10086out.write(b, 0, len);}System.out.println("发送完成。");} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fis != null)fis.close();s.close();} catch (IOException e) {e.printStackTrace();}}}public static void server() {ServerSocket ss = null;Socket s = null;FileOutputStream fis = null;// 以10086作为服务端try {System.out.println("服务端开启...");ss = new ServerSocket(10086);System.out.println("等待客户端连接...");s = ss.accept();InputStream in = s.getInputStream();fis = new FileOutputStream("晴天2.mp3");byte[] b = new byte[1024*8]; int len;while ((len = in.read(b)) != -1) {fis.write(b, 0, len);}System.out.println("上传成功。");} catch (IOException e) {e.printStackTrace();}}
}