首先讓我們看看最簡單的socket client與server實例: Client Server 以上一個Client和一個Server,最簡單的例子,但是體現socket編程。 如果需要Server服務端一直監聽埠,那麼只需要迴圈就可以(server.accept()會阻塞等待請求),至於需要高 ...
首先讓我們看看最簡單的socket client與server實例:
Client
public class MyClient { public static void main(String[] args) { ObjectOutputStream oos = null; ByteArrayOutputStream bos = null; Socket client = null; try { People p = new People("2","yangyu","4","5","6"); oos = new ObjectOutputStream(bos = new ByteArrayOutputStream()); //初始化object輸出流 oos.writeObject(p); //將People對象寫入輸出流 byte[] bytes = bos.toByteArray(); //獲取People對象的byte數組(也就是序列化People) client = new Socket("127.0.0.1",20007); //連接127.0.0.1的20007埠 client.setSoTimeout(10000); //設置超時時間 client.getOutputStream().write(bytes); //向server發送byte[]數組 byte[] bytes1 = IOUtils.readFully(client.getInputStream(),18,false); //獲取server返回數據 System.out.println(new String(bytes1)); System.out.println(bytes1.length); } catch (Exception e) { e.printStackTrace(); }finally { try { oos.close(); bos.close(); System.out.println(client.isClosed()); client.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Server
public class MyServer { public static void main(String[] args) { ServerSocket server = null; Socket client = null; ObjectInputStream ois = null; ByteArrayInputStream bis = null; try { server = new ServerSocket(20007); //啟動Socket server,監聽20007埠 client = server.accept(); //阻塞並等待接收客戶端發送數據並生成client byte[] bytes = IOUtils.readFully(client.getInputStream(),-1,false);//獲取客戶端發送過來的數據 bis = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bis); People people = (People) ois.readObject();//反序列化 System.out.println("people name:"+people.getName()); String res = "消息已經收到"; client.getOutputStream().write(res.getBytes());//向客戶端發送數據 } catch (Exception e) { e.printStackTrace(); }finally { try { bis.close(); ois.close(); client.close(); server.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上一個Client和一個Server,最簡單的例子,但是體現socket編程。
如果需要Server服務端一直監聽埠,那麼只需要迴圈就可以(server.accept()會阻塞等待請求),至於需要高併發的響應,那麼Server對數據業務的處理交由線程池來做吧。