socket programming

来源:互联网 发布:莎莎源码是什么意思 编辑:程序博客网 时间:2024/05/17 05:00

代码1

package com.pc.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.nio.CharBuffer;public class HttpFileSocketServer {private int port = 8080;private String url = "localhost";private boolean shutdown = false;public void start() throws IOException {InetAddress bindAddr = InetAddress.getByName(url);ServerSocket serverSocket = new ServerSocket(port, 1/* backlog */,bindAddr);System.out.println(String.format("socket server started @ %s:%s...",url, port));Socket socket = null;while (!shutdown) {socket = serverSocket.accept();// System.out.println("socket accepted...");BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));// ************* New IOCharBuffer charBuffer = CharBuffer.allocate(1024);System.out.println("**** received from client ****");int tmp = 0;//idiot!! socket will keep reading the input channel! seems never reach -1 or null//while ((tmp = in.read(charBuffer)) != -1) {in.read(charBuffer);charBuffer.flip();System.out.print(charBuffer);if(charBuffer.toString().contains("shutdown"))shutdown=true;//http://localhost:8080/shutdowncharBuffer.clear();System.out.println("response to client...");OutputStream out = socket.getOutputStream();String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +    "Content-Type: text/html\r\n" +    "Content-Length: 23\r\n" +    "\r\n" +    "<h1>File Not Found</h1>";out.write(errorMessage.getBytes());        out.flush();out.close();in.close();socket.close();System.out.println("Done.");}serverSocket.close();}public static void main(String[] args) {try {new HttpFileSocketServer().start();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

代码2

package com.pc.tmp;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;public class SendFileViaSocketUseHttp {static boolean isNormalShutDown = false;/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubtry {InetAddress i = InetAddress.getLocalHost();//InetAddress i = InetAddress.getByName("127.0.0.1");int port = 80;final ServerSocket svr = new ServerSocket(port,1,i);new Thread(new Runnable() {@Overridepublic void run() {System.out.println("Control thread started...");try {Thread.sleep(3000);if(!svr.isClosed()){System.out.println("Control thread receive STOP signal, will shutdown the socket right now!");isNormalShutDown = true;svr.close();}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();System.out.println("listening address: " + i +":"+ port);Socket s = svr.accept();System.out.println("socket accepted...");InputStream is = s.getInputStream();OutputStream os = s.getOutputStream();// String httpHeader = "HTTP/1.1 200 OK\nContent-Disposition:attachment; filename=PAUL.doc\n\n";os.write(httpHeader.getBytes());File f = new File("C:/Users/Administrator/Desktop/java.doc");System.out.println("socket transferring ["+f.getName()+"]...");BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));byte[] b = new byte[1024];while((bis.read(b))!=-1){os.write(b);}bis.close();is.close();os.close();s.close();svr.close();System.out.println("completed.");} catch (IOException e) {if(isNormalShutDown!=true)e.printStackTrace();}}}

输出:

Control thread started...
listening address: 81C9SCKURB9SGQY/192.168.1.101:80
Control thread receive STOP signal, will shutdown the socket right now!


代码3

Open HTTP URL using proxy: (haha, can escape company's download file firewall on IE)

package com.pc.ws.client;import java.io.IOException;import java.io.InputStream;import java.net.InetSocketAddress;import java.net.MalformedURLException;import java.net.Proxy;import java.net.URL;import java.net.URLConnection;public class TryURLOpenHttp {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {String address = "http://code.jquery.com/jquery-1.8.0.min.js";//address = "http://www.baidu.com";URL url = new URL(address);Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("svr1.xx.xxxx", 8080));URLConnection connection = url.openConnection(proxy);InputStream is = connection.getInputStream();//url.openStream();//byte[] bytes = new byte[1024];int tm;while( (tm = is.read(bytes)) != -1){System.out.print(new String(bytes));}}}









原创粉丝点击