http://www.javaworld.com.tw/jute/post/view?bid=6&id=212188&sty=3&age=0&tpg=1&ppg=1#212188
首先 web.xml里的配置为:
1
|
<servlet> <servlet-name>socketservlet</servlet-name> <servlet-class>com.bluepure.SocketServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> |
load-on-startup是用来控制在web启动的时候就初始化serverlet,也就是调用其init方法.
servlet代码为:
1
|
package com.bluepure; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SocketServlet extends HttpServlet { Myserver myserver = null; public void init() throws ServletException { super.init(); myserver = new Myserver(); myserver.startServer(); System.out.println("启动Socket server"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("nothing"); out.close(); } public void destroy() { super.destroy(); System.out.println("关闭Socket server"); if (myserver != null) { myserver.stopServer(); } } } |
独立的Server代码为:
1
|
package com.bluepure; import java.net.*; import java.io.*; public class Myserver extends Thread { private boolean started = false; private int port = 3333; public Myserver() { } public void run() { try { ServerSocket server = new ServerSocket(port); while (started) { final Socket socket = server.accept(); new Thread() { public void run() { try { InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); java.io.BufferedReader bis = new BufferedReader(new InputStreamReader(is, "UTF-8")); String s = null; while ((s = bis.readLine()) != null) { System.out.println("s==" + s); //将客户端输入的内容变成大写再写回 os.write(("uppercase is : " + s + "\r\n"). toUpperCase(). getBytes()); //如果是退出指令,则关闭Socket if ("quit".equalsIgnoreCase(s)) { os.write("BYE\r\n".getBytes()); bis.close(); os.close(); socket.close(); break; } } } catch (Exception ex) { ex.printStackTrace(); } } }.start(); } server.close(); } catch (IOException ex) { ex.printStackTrace(); } } public void startServer() { started = true; this.start(); } public void stopServer() { started = false; ; } } |
全站熱搜
留言列表