相关Java类
Socket
public class Socket extends Object
・功能:TCP客户端套接字・构造方法: Socket(InetAddress address, int port) 创建一个流套接字并将其连接到指定 IP 地址的指定端口号・常用方法: 1.getInetAddress 获得InetAddress的相关信息 2.getInputStream 获得此TCP连接的输入流 3.getOutPutStream 获得此TCP连接的输出流
ServerSocket
public class ServerSocket extends Object
・功能: TCP服务端套接字・构造方法: ServerSocket(int port) 创建绑定到特定端口的服务器套接字。・常用方法: 1.accept 获得TCP连接的客户端的socket 2.isClosed 获得ServerSocket的关闭状态
TCP服务器端
TcpServer.java
服务器端采用多线程的方式,每建立一个连接就启动一个java线程,发送图片给客户端,之后关闭此TCP连接
package cn.xidian.tcpSocket;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();//获取客户端的OutputStreamOutputStream 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
package cn.xidian.tcpSocket;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();}}结果
首先,命令行启动服务器端,之后启动客户端,结果如下:
图片比较小,速度很快!
总结
以上就是本文关于Java编程实现多线程TCP服务器完整实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!