Java网络编程实例---------------------------------基本HTTP客户端及服务端多线程
HTTP 1.0客户端
package com.bq; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; public class Client { public Client() throws Exception { Socket server = new Socket(InetAddress.getLocalHost(), 8000); BufferedReader in = new BufferedReader(new InputStreamReader( server.getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while (true) { String str = wt.readLine(); out.println(str); out.flush(); if (str.equals("end")) { break; } System.out.println(in.readLine()); } server.close(); } public static void main(String[] args) throws Exception { new Client(); } }
HTTP Server
package com.bq; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public Server() throws IOException { ServerSocket server = new ServerSocket(8000); Socket client = server.accept(); BufferedReader in = new BufferedReader(new InputStreamReader( client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while (true) { String str = in.readLine(); System.out.println(str); out.println("Receive from Client...." + str.toUpperCase()); out.flush(); if (str.equals("quit")) break; } client.close(); } public static void main(String[] args) throws IOException { new Server(); } }
HTTP Server 多线程
package com.bq; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class ThreadedServer { public ThreadedServer() throws Exception { ServerSocket server = new ServerSocket(8000); int socketNo = 1; while (true) { Socket socket = server.accept(); System.out.println("----Start For socket No" + socketNo + "------"); System.out.println("The socket name =======" + socket.getInetAddress().getHostName()); HandleAsocket task = new HandleAsocket(socket); new Thread(task).start(); socketNo++; } } public static void main(String[] args) throws Exception { new ThreadedServer(); } } class HandleAsocket implements Runnable { private Socket socket; public HandleAsocket(Socket socket) { this.socket = socket; } @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); while (true) { String str = in.readLine(); System.out.println(str); out.println("Receive from socket...." + str.toUpperCase()); out.flush(); if (str.equals("quit")) break; } socket.close(); } catch (Exception e) { e.printStackTrace(); } } }