通过java socket通讯(一) 入门示例,就可以实现服务端和客户端的socket通讯,但是上一个例子只能实现一个服务端和一个客户端之间的通讯,如果有多个客户端连接服务端,则需要通过多线程技术来实现。
服务器端----------------------------------------------------------------------------------------------------------------------------------------
socketServer:
package test; import java.net.ServerSocket; import java.net.Socket; public class socketServer { public static void main(String [] args){ ServerSocket ss = null; Socket sk = null; try{ System.out.println("create server socket...."); ss = new ServerSocket(3756); System.out.println("wait for a connection...."); while(true) //服务器端一直监听这个端口,等待客户端的连接 { sk = ss.accept(); //当有客户端连接时,产生阻塞 System.out.println("get a socket object..."); new socketThread(sk).start();//新建一个socketThread处理这个客户端的socket连接 } } catch(Exception ex){ System.out.println(ex.getMessage()); } finally{ try{ if(ss != null){ ss.close(); } if(sk != null){ sk.close(); } } catch(Exception ex){ System.out.println(ex.getMessage()); } } } }
socketThread:
package test; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.*; public class socketThread extends Thread { public Socket socket; public socketThread(Socket socket) { this.socket = socket; } public void run() { PrintWriter pw = null; Calendar c; try { pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); while(true)//服务器每隔3秒向客户端发送当前时间信息 { Thread.sleep(3000); c = Calendar.getInstance(); //获取当前时间 pw.println("Server Time:"+c.getTime().toString()); pw.flush(); } } catch (Exception ex) { System.out.println(ex.getMessage()); } finally { try { if (pw != null) { pw.close(); } if (socket != null) { socket.close(); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } } }
客户端----------------------------------------------------------------------------------------------------------------------------------------
socketClient:
package test; import java.io.PrintWriter; import java.net.Socket; import java.io.InputStreamReader; import java.io.BufferedReader; public class socketClient { public static void main(String[] args) { Socket sk = null; BufferedReader br = null; try { sk = new Socket("localhost", 3756); br = new BufferedReader(new InputStreamReader(sk.getInputStream())); String line = null; while((line = br.readLine()) != null){ System.out.println("Msg from server:"+line); //服务器端打印客户端发送的信息数据 } } catch (Exception ex) { System.out.println(ex.getMessage()); } finally { try { if (sk != null) { sk.close(); } if (br != null) { br.close(); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } } }
服务端启动后,就会监听3756端口,每当有一个客户端请求时,就会新建一个socketThread来和客户端进行通讯(每隔3秒钟将服务端的时间发送到客户端)