{建立服务器}
import java.net.*;import java.io.*;public class Server{private ServerSocket ss;private Socket socket;private BufferedReader in;private PrintWriter out;public Server(){try{ss = new ServerSocket(10000);while (true){socket = ss.accept();in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out = new PrintWriter(socket.getOutputStream(),true);String line = in.readLine();out.println("you input is :" + line);out.close();in.close();socket.close();}ss.close();}catch (IOException e){}}public static void main(String[] args){new Server();}}
这个程序建立了一个服务器,它一直监听10000端口,等待用户连接。在建立连接后给客户端返回一段信息,然后结束会话。这个程序一次只能接受一个客户连接。
{建立客户端}
import java.io.*;import java.net.*;public class Client{Socket socket;BufferedReader in;PrintWriter out;public Client(){try{socket = new Socket("xxx.xxx.xxx.xxx", 10000);in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out = new PrintWriter(socket.getOutputStream(),true);BufferedReader line = new BufferedReader(new InputStreamReader(System.in));out.println(line.readLine());line.close();out.close();in.close();socket.close();}catch (IOException e){}}public static void main(String[] args){new Client();}}这个客户端连接到地址为xxx.xxx.xxx.xxx的服务器,端口为10000,并从键盘输入一行信息,发送到服务器,然后接受服务器的返回信息,最后结束会话。 第二步 多个客户同时连接 在实际的网络环境里,同一时间只对一个用户服务是不可行的。一个优秀的网络服务程序除了能处理用户的输入信息,还必须能够同时响应多个客户端的连接请求。在java中,实现以上功能特点是非常容易的。 设计原理: 主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。运用Thread类或Runnable接口来实现是不错的办法。 {实现消息共享}
import java.io.*;import java.net.*;public class Server extends ServerSocket{private static final int SERVER_PORT = 10000;public Server() throws IOException{super(SERVER_PORT);try{while (true){Socket socket = accept();new CreateServerThread(socket);}}catch (IOException e){}finally{close();}}//--- CreateServerThreadclass CreateServerThread extends Thread{private Socket client;private BufferedReader in;private PrintWriter out;public CreateServerThread(Socket s) throws IOException{client = s;in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312"));out = new PrintWriter(client.getOutputStream(), true);out.println("--- Welcome ---");start();}public void run(){try{String line = in.readLine();while (!line.equals("bye")){String msg = createMessage(line);out.println(msg);line = in.readLine();}out.println("--- See you, bye! ---");client.close();}catch (IOException e){}}private String createMessage(String line){xxxxxxxxx;}}public static void main(String[] args) throws IOException{new Server();}}这个程序监听10000端口,并将接入交给CreateServerThread线程运行。CreateServerThread线程接受输入,并将输入回应客户,直到客户输入"bye",线程结束。我们可以在createMessage方法中,对输入进行处理,并产生结果,然后把结果返回给客户。 第三步 实现信息共享:在Socket上的实时交流 网络的伟大之一也是信息共享,Server可以主动向所有Client广播消息,同时Client也可以向其它Client发布消息。下面看看如何开发一个可以实时传递消息的程序。
设计原理: 服务器端接受客户端的连接请求,同时启动一个线程处理这个连接,线程不停的读取客户端输入,然后把输入加入队列中,等候处理。在线程启动的同时将线程加入队列中,以便在需要的时候定位和取出。 {源码}
import java.io.*;import java.net.*;import java.util.*;import java.lang.*;public class Server extends ServerSocket{private static ArrayList User_List = new ArrayList();private static ArrayList Threader = new ArrayList();private static LinkedList Message_Array = new LinkedList();private static int Thread_Counter = 0;private static boolean isClear = true;protected static final int SERVER_PORT = 10000;protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);public Server() throws FileNotFoundException, IOException{super(SERVER_PORT);new Broadcast();//append connection logCalendar now = Calendar.getInstance();String str = "[" + now.getTime().toString() + "] Accepted a connection\015\012";byte[] tmp = str.getBytes();LOG_FILE.write(tmp);try{while (true){Socket socket = accept();new CreateServerThread(socket);}}finally{close();}}public static void main(String[] args) throws IOException{new Server();}//--- Broadcastclass Broadcast extends Thread{public Broadcast(){start();}public void run(){while (true){if (!isClear){String tmp = (String)Message_Array.getFirst();for (int i = 0; i < Threader.size(); i++){CreateServerThread client = (CreateServerThread)Threader.get(i);client.sendMessage(tmp);}Message_Array.removeFirst();isClear = Message_Array.size() > 0 ? false : true;}}}}//--- CreateServerThreadclass CreateServerThread extends Thread{private Socket client;private BufferedReader in;private PrintWriter out;private String Username;public CreateServerThread(Socket s) throws IOException{client = s;in = new BufferedReader(new InputStreamReader(client.getInputStream()));out = new PrintWriter(client.getOutputStream(), true);out.println("--- Welcome to this chatroom ---");out.println("Input your nickname:");start();}public void sendMessage(String msg){out.println(msg);}public void run(){try{int flag = 0;Thread_Counter++;String line = in.readLine();while (!line.equals("bye")){if (line.equals("l")){out.println(listOnlineUsers());line = in.readLine();continue;}if (flag++ == 0){Username = line;User_List.add(Username);out.println(listOnlineUsers());Threader.add(this);pushMessage("[< " + Username + " come on in >]");}else{pushMessage("<" + Username + ">" + line);}line = in.readLine();}out.println("--- See you, bye! ---");client.close();}catch (IOException e){}finally{try{client.close();}catch (IOException e){}Thread_Counter--;Threader.remove(this);User_List.remove(Username);pushMessage("[< " + Username + " left>]");}}private String listOnlineUsers(){String s ="-+- Online list -+-\015\012";for (int i = 0; i < User_List.size(); i++){s += "[" + User_List.get(i) + "]\015\012";}s += "-+---------------------+-";return s;}private void pushMessage(String msg){Message_Array.addLast(msg);isClear = false;}}}这就是程序运行后,多用户登陆并且输入信息后的屏幕。实现了信息的实时广播。用户输入"l"就可以列出在线人员表。