數據發送端(客戶端):
//創建一個Socket對象,連接IP地址為192.168.101.56的服務器的9002端口 Socket s = new Socket("192.168.101.56",9002);
//xml內容
String fix="<?xml version=\"1.0\" encoding=\"UTF-8\"?><MESSAGE>XXX</MESSAGE>";
byte[] b= fix.getBytes(); int xmlleng=b.length;
//2是包頭長度,第一個4是xml內容長度,第二個4是包尾長度,為了程序的閱讀性良好,建議定義成變量或常量
int pacLen= 2+xmlleng+4+4; byte[] content=new byte[pacLen]; //包頭 content[0]=(byte) 0xE2; content[1]=(byte) 0x5C; //xml內容 for(int i=0;i<b.length;i++){ content[i+2]=b[i]; } //計算XML格式數據的長度 content[pacLen-8] = (byte) xmlleng; content[pacLen-7] = (byte) (xmlleng >> 8); content[pacLen-6] = (byte) (xmlleng >> 16); content[pacLen-5] = (byte) (xmlleng >> 24);
//包尾 content[pacLen-4] = (byte) 0x00; content[pacLen-3] = (byte) 0x00; content[pacLen-2] = (byte) 0x00; content[pacLen-1] = (byte) 0xff;
//傳輸字節流
DataOutputStream output=new DataOutputStream(s.getOutputStream());
output.write(content, 0, content.length);
output.close();
//關閉Socket連接
s.close();
數據接收端(服務器端):
ServerSocket ss = new ServerSocket(9002); //創建一個Socket服務器,監聽9002端口 Socket s = ss.accept();//利用Socket服務器的accept()方法獲取客戶端Socket對象。 //獲取二進制流 DataInputStream input=new DataInputStream(s.getInputStream()); byte[] buffer = new byte[20480]; //消息長度 int rlength=input.read(buffer, 0, 20480); System.out.println(); System.out.println("接收的消息長度:"+rlength); //傳輸的實際byte[] byte[] buffer1 = new byte[rlength]; for(int i=0;i<buffer1.length;i++){ buffer1[i]=buffer[i]; } String messageContent1=new String(buffer1,"GBK").toString().trim(); System.out.println("接收的消息(gbk轉碼):"+messageContent1); String messageContent=new String(buffer,0,rlength).toString().trim(); System.out.println("接收的消息:"+messageContent);
input.close();
s.close();
簡單的說,客戶端
①需要知道服務端的地址,端口,然后通過地址和端口建立連接(服務端必須先啟動,否則建立不了連接)
②然后通過流將數據傳輸過去
服務器端
①需要確定使用哪個接口,如例子里使用的9002端口 ServerSocket ss = new ServerSocket(9002)
②然后 利用Socket服務器的accept()方法獲取客戶端Socket對象(即例子里 Socket s = ss.accept())
注意:如果沒有客戶端申請建立連接,即Socket s = ss.accept()接收不到客戶端對象,那么在 Socket s = ss.accept()之后的代碼就不會執行。
③通過流接收數據