Socket
·功能:TCP客户端套接字
·构造方法:
Socket(InetAddress address, int port)
创建一个流套接字并将其连接到指定 IP 地址的指定端口号
·常用方法:
1.getInetAddress
获得InetAddress的相关信息
2.getInputStream
获得此TCP连接的输入流
3.getOutPutStream
获得此TCP连接的输出流
ServerSocket
·功能: TCP服务端套接字
·构造方法:
ServerSocket(int port)
创建绑定到特定端口的服务器套接字。
·常用方法:
1.accept
获得TCP连接的客户端的socket
2.isClosed
获得ServerSocket的关闭状态
TCP服务器端
TcpServer.java
服务器端采用多线程的方式,每建立一个连接就启动一个java线程,发送图片给客户端,之后关闭此TCP连接
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TcpServer extends Thread{ Socket clientSocket; public TcpServer(Socket clientSocket) { super(); this.clientSocket = clientSocket; } @Override public void run() { try { //获得客户端的ip地址和主机名 String clientAddress = clientSocket.getInetAddress().getHostAddress(); String clientHostName = clientSocket.getInetAddress().getHostName(); System.out.println(clientHostName + "(" + clientAddress + ")" + " 连接成功!"); System.out.println("Now, 传输图片数据..........."); long startTime = System.currentTimeMillis(); //获取客户端的OutputStream OutputStream out = clientSocket.getOutputStream(); //传出图片数据 FileInputStream in = new FileInputStream(new File("/home/gavinzhou/test.jpg")); byte[] data = new byte[4096]; int length = 0; while((length = in.read(data)) != -1){ out.write(data, 0, length); //写出数据 } long endTime = System.currentTimeMillis(); //提示信息 System.out.println(clientHostName + "(" + clientAddress + ")" + " 图片传输成功," + "用时:" + ((endTime-startTime)) + "ms"); //关闭资源 in.close(); clientSocket.close(); System.out.println("连接关闭!"); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { //建立TCP连接服务,绑定端口 ServerSocket tcpServer = new ServerSocket(9090); //接受连接,传图片给连接的客户端,每个TCP连接都是一个java线程 while(true){ Socket clientSocket = tcpServer.accept(); new TcpServer(clientSocket).start(); } } }
TCP客户端
TcpClient
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; public class TcpClient { public static void main(String[] args) throws IOException { // 建立TCP服务 // 连接本机的TCP服务器 Socket socket = new Socket(InetAddress.getLocalHost(), 9090); // 获得输入流 InputStream inputStream = socket.getInputStream(); // 写入数据 FileOutputStream out = new FileOutputStream(new File("../save.jpg")); byte[] data = new byte[4096]; int length = 0; while((length = inputStream.read(data)) != -1){ out.write(data, 0, length); } //关闭资源 out.close(); socket.close(); } }
结果
首先,命令行启动服务器端,之后启动客户端,结果如下:
图片比较小,速度很快!