`
javaliver
  • 浏览: 20996 次
  • 性别: Icon_minigender_1
  • 来自: 伊拉克
社区版块
存档分类
最新评论

Client ,Server基于socket 的图片上传(WEB)

阅读更多

 

服务器端:

 

	<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 监听其它客户机的连接请求。

分享到:
评论

相关推荐

    利用socket 编写web 服务器的源代码

    我们将基于标题和描述中的内容,讲解socket编程的基本概念、Web服务器的工作原理以及如何用源代码实现这一过程。 一、Socket编程基础 Socket,通常称为套接字,是进程间通信的一种方式,它允许两个网络应用程序之间...

    用socket实现的最简单的web服务器示例

    client_socket, addr = server_socket.accept() print(f"Connected by {addr}") request = client_socket.recv(1024).decode('utf-8') print("Request: ", request) response = "HTTP/1.1 200 OK\n\nHello,...

    C#Socket_Server+Client及簡單使用Client異常時重連.zip

    本压缩包中的"C#Socket_Server+Client及簡單使用Client異常時重連.zip"包含了一个C#实现的Socket服务器和客户端示例,特别强调了客户端在网络中断后的自动重连功能。下面将详细介绍相关知识点。 首先,C#中的Socket...

    基于socket通讯的聊天室

    源代码可能包括了Server.cs(服务器端程序)和Client.cs(客户端程序),它们分别实现了上述的Socket通信流程。通过阅读和理解这些代码,你可以更深入地学习如何在C#中使用Socket实现网络通信,以及如何设计和实现一...

    WebSocket.zip_Server_client_rights_web socket_websocket

    Websocket-Arduino, a websocket implementation for Arduino ... Based on previous implementations by ...and ...and ... Some code and concept based off of Webduino library ...Permission is hereby granted, free of ...

    基于socket.io的聊天室

    【基于socket.io的聊天室】 在信息技术领域,实时通信已经成为了一项重要的需求,尤其是在Web应用中。基于Node.js的Express框架和socket.io库,开发者可以创建出高效的实时交互应用程序,如聊天室。本项目就是一个...

    linux基于socket

    ### Linux 下基于 Socket 的 BS 架构 Web 服务器 在 Linux 操作系统中,网络通信是通过套接字(Socket)实现的。本篇文章将基于一个简单的示例代码,介绍如何利用 Socket 在 Linux 下构建一个基本的 BS 构架 Web ...

    Socket 简单通信程序 Server Client

    Socket编程是计算机网络编程中的重要组成部分,主要用于实现客户端(Client)和服务器端(Server)之间的通信。在这个"Socket简单通信程序Server Client"中,我们将会深入理解Socket的工作原理及其在TCP/IP协议栈中...

    linux socket server和client

    本篇将详细讲解Linux Socket服务器(Server)和客户端(Client)的实现及其相关知识点。 首先,让我们了解一下Socket的基本概念。Socket可以看作是两台计算机之间通信的端点,它包含了一个IP地址和一个端口号,用于...

    基于socket的C/S程序(vb2008源码)

    标题中的“基于socket的C/S程序(vb2008源码)”指的是使用VB.NET 2008开发的客户端/服务器(Client/Server,C/S)应用程序,该程序利用了Socket编程来实现网络通信。Socket是网络编程的基础,它提供了一种在不同...

    Webserver基于Ws

    本话题聚焦于一种基于Ws(WebSocket)服务的Web服务器,这是一个允许双向通信的协议,极大地提升了实时性,特别适用于实时聊天、在线游戏、股票交易等场景。下面我们将深入探讨基于Ws的Web服务器及其客户端的入门...

    socket编程基于tcp的通信

    client_socket, _ = server_socket.accept() data = client_socket.recv(1024) client_socket.sendall(data.upper()) client_socket.close() ``` 在这个例子中,服务器接收来自客户端的数据,将其转换为大写并...

    C#基于socket通讯服务器端

    C#是一种广泛用于构建桌面、Web和移动应用的编程语言,它提供了丰富的库来支持网络编程,其中Socket通信是最基础也是最常用的方式之一。本篇文章将详细讲解如何在C#中实现基于Socket的服务器端。 首先,我们需要...

    Python学习笔记-基于socket基础的http服务端程序

    client_socket, addr = server_socket.accept() print(f"接收到来自{addr}的连接请求") # 接收客户端发送的数据 request_data = client_socket.recv(1024).decode('utf-8') # 分析请求,处理HTTP请求行 ...

    异步Socket(server and client)

    - 高性能Web服务器,如Nginx、Apache等,使用异步Socket提高并发处理能力。 - 日志收集服务,异步接收多个客户端的日志数据。 8. 相关工具和库: - .NET Framework提供了System.Net.Sockets命名空间,支持异步...

    node-websocket-client, NodeJS的Web Socket客户端.zip

    node-websocket-client, NodeJS的Web Socket客户端 一个 Prototype Web Socket 客户端实现 node.js 。测试 miksago/node-websocket-server v1.2.00.需要 nodejs 0.1.98或者更高版本。安装按如下方式使用 np

    Java 在Client-Server 网络中的应用

    ### Java在Client-Server网络中的应用详解 #### 一、Java网络应用模型 随着Java语言的广泛应用及其与互联网的高度融合,Java已经成为构建现代信息系统的重要工具之一。Java的特点,如跨平台性、面向对象的设计理念...

    一个简单而强大的基于MFC的web server源码

    【标题】:基于MFC的Web服务器源码解析 在IT行业中,开发一款Web服务器是一项技术挑战,而本文将深入探讨一个使用Microsoft Foundation Class (MFC)库构建的简单但功能强大的Web服务器源码。MFC是微软为Windows平台...

    socket.io认证,nodejs实现socket.io demo(server/client)

    Socket.IO 是一个实时应用框架,它为Web开发者提供了一种简单、高效的通信方式,支持WebSocket以及其他多种降级机制。在Node.js环境中,Socket.IO能够帮助我们构建实时、双向且连接持久的应用,比如在线聊天、实时...

Global site tag (gtag.js) - Google Analytics