Socketjava
·功能:TCP客户端套接字
服务器
·构造方法:
Socket(InetAddress address, int port)
建立一个流套接字并将其链接到指定 IP 地址的指定端口号
·经常使用方法:
1.getInetAddress
得到InetAddress的相关信息
2.getInputStream
得到此TCP链接的输入流
3.getOutPutStream
得到此TCP链接的输出流
·功能: TCP服务端套接字
·构造方法:
ServerSocket(int port)
建立绑定到特定端口的服务器套接字。
·经常使用方法:
1.accept
得到TCP链接的客户端的socket
2.isClosed
得到ServerSocket的关闭状态
TCP服务器端多线程
TcpServer.javasocket
服务器端采用多线程的方式,每创建一个链接就启动一个java线程,发送图片给客户端,以后关闭此TCP链接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客户端ide
TcpClientthis
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(); } }
结果spa
首先,命令行启动服务器端,以后启动客户端,结果以下:.net
图片比较小,速度很快!命令行