?
服务器端:
?
<servlet> <description> This is the description of my J2EE component </description> <display-name> This is the display name of my J2EE component </display-name> <servlet-name>InitServlet</servlet-name> <servlet-class>com.dne.pg.servlet.InitServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>InitServlet</servlet-name> <url-pattern>/servlet/InitServlet</url-pattern> </servlet-mapping>?
?
?
package com.javaliver.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.Globals; import com.javaliver.file.FileTransServer; public class InitServlet extends HttpServlet { /** * Constructor of the object. */ public InitServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute(Globals.LOCALE_KEY, Locale.ENGLISH); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute(Globals.LOCALE_KEY, Locale.ENGLISH); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occure */ public void init() throws ServletException { // Put your code here new Thread(new FileTransServer()).start(); } }?
?
package com.javaliver.file.socket; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import org.apache.log4j.Logger; public class FileTransServer implements Runnable { private int port = 9992; private ServerSocket serverSocket = null; private boolean isRuning; private static final Logger log = Logger.getLogger(FileTransServer.class); public FileTransServer() { } public void run(){ isRuning = true; try { serverSocket = new ServerSocket(port); } catch (IOException e1) { e1.printStackTrace(); } while(isRuning){ try { log.info("FileTransServerSocket()*********step1 ;port is "+port); Socket socket = serverSocket.accept(); FileTransServerSocket cs = new FileTransServerSocket(); cs.setSocket(socket); log.info("开始处理线程" + cs.getSocket().getRemoteSocketAddress().toString()); new Thread(cs).start(); } catch (Exception e) { log.info("FileTransServerSocket()*********step1 ****it is not usual!;"); e.printStackTrace(); } finally { } } } }
?
package com.javaliver.file.socket; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import org.apache.log4j.Logger; public class FileTransServerSocket implements Runnable { private DataOutputStream out = null; private Socket socket; private DataInputStream getMessageStream = null; private static final Logger log = Logger.getLogger(FileTransServerSocket.class); public FileTransServerSocket() {} public void run(){ try { this.handleConnection(this.socket); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void handleConnection(Socket socketConnection) throws Exception { DataInputStream inputStream = null; try { inputStream = new DataInputStream(new BufferedInputStream( socketConnection.getInputStream())); } catch (Exception e) { e.printStackTrace(); if (inputStream != null) inputStream.close(); System.out.print("接收消息缓存错误\n"); throw e; } try { int bufferSize = 8192; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len = 0; if(inputStream==null){ System.out.println("没有读取到图片名称"); return ; } System.out.println("读取文件名称"); String passFileName = inputStream.readUTF(); String savePath = getSavePath() + "\\"+passFileName; DataOutputStream fileOut = new DataOutputStream( new BufferedOutputStream(new BufferedOutputStream( new FileOutputStream(savePath)))); if(inputStream==null){ System.out.println("没有读到文件长度"); return ; } len = inputStream.readLong(); log.info("文件的长度为:" + len + "\n"); log.info("开始接收文件!" + "\n"); while (true) { int read = 0; if (inputStream != null) { read = inputStream.read(buf); } passedlen += read; if (read == -1) { break; } log.info("文件接收了" + (passedlen * 100 / len) + "%\n"); fileOut.write(buf, 0, read); } log.info("接收完成,文件存为" + savePath + "\n"); if(fileOut!=null){ fileOut.flush(); fileOut.close(); } if(inputStream!=null){ inputStream.close(); } socketConnection.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.getStackTrace(); log.info("接收消息错误" + "\n"+e.getStackTrace()+e.getMessage()); return; } } private String getSavePath() { PropertyResourceBundle res =(PropertyResourceBundle) ResourceBundle.getBundle("Framework"); String tomcatPath=System.getProperty("catalina.home"); tomcatPath=tomcatPath.replace("/", File.separator) +"/webapps"; String savePath= tomcatPath + res.getString("imagepath"); savePath = savePath.replace("/", File.separator); return savePath; } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } }
?
?
1:serverSocket = new ServerSocket(port);
?
当服务器(Tomcat)启动加载的时候InitServlet 创建了一个能监听某些客户机访问的入口
FileTransServer 在9992端口上监听。
?
2:Socket socket = serverSocket.accept();
创建了一个新的套接字,称为socket,这个套接字也是用9992端口
?
客户端的测试类:
import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SocketU { // private String ip = "";// 设置成服务器IP private String ip = "localhost"; private int port = 9992; private String sendMessage = "C:\\1.gif";// 这个路径你自己读取的照片的位置 Socket socketConnection = null; DataOutputStream sendMsg = null; DataInputStream getMsg = null; DataInputStream fis = null; public static void main(String arg[]) throws Exception { SocketU clientTest = new SocketU(); clientTest.setUpConnection(); clientTest.sendMessage(); } public void setUpConnection() { try { socketConnection = new Socket(ip, port); sendMsg = new DataOutputStream(socketConnection.getOutputStream()); getMsg = new DataInputStream(new BufferedInputStream( socketConnection.getInputStream())); } catch (UnknownHostException e) { System.out.println("连接错误: 未知主机 " + sendMessage + ":" + port); } catch (IOException e) { System.out.println("连接时出错: " + e); } } private void sendMessage() throws Exception { try { File img = new File(sendMessage); if (img.exists()) { fis = new DataInputStream(new BufferedInputStream( new FileInputStream(img))); sendMsg.writeUTF(img.getName()); sendMsg.flush(); sendMsg.writeLong((long) img.length()); sendMsg.flush(); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; while (true) { Thread.sleep(1L); int read = 0; if (fis != null) { read = fis.read(buf); } if (read == -1) { break; } System.out.println("File Saved-----------------" + read + "%\n"); sendMsg.write(buf, 0, read); } } if (fis != null) { fis.close(); } socketConnection.close(); sendMsg.flush(); if (sendMsg != null) { sendMsg.close(); } System.out.println("Upload File Over!!!"); } catch (Exception e) { e.printStackTrace(); } finally { } } }?
?
?
?
TCP在客户端的clientSocket和服务器端的socket之间建立了一条直接的虚礼管道,该客户机与服务器可以通过该管道彼此发送字节,并且发送的所有字节将按顺序到达对方。随着socket的建立,该服务器能继续使用serverSocket 监听其它客户机的连接请求。