資源描述:
《以聊天為例講解關于Android_的socket編程》由會員上傳分享,免費在線閱讀,更多相關內容在工程資料-天天文庫。
1、關于Android的socket編程【以聊天為例】下面,用敲門的方式演示Android如何實現套接字的通信。本例實現功能如下:Server端開啟服務Client端發(fā)起鏈接請求,并向Server端發(fā)送數據Server端響應請求,并在Server顯示,向Client端返回數據Client端接收Server的數據并顯示本例效果如下:終端1:終端2:Server端:本例源代碼如下:Server端:packagecom.android.Yao;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.IO
2、Exception;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassYaoChatServerextendsThread{privateYaoChatServer()throwsIOException{CreateSocket();//創(chuàng)建Socket服務器}publicvoidrun(){Socketclient;Stringtxt;try{while(true)//線程無限循
3、環(huán),實時監(jiān)聽socket端口{client=ResponseSocket();//響應客戶端鏈接請求。。while(true){txt=ReceiveMsg(client);System.out.println(txt);//鏈接獲得客戶端發(fā)來消息,并將其顯示在Server端的屏幕上SendMsg(client,txt);//向客戶端返回消息if(true)break;//中斷,繼續(xù)等待鏈接請求}CloseSocket(client);//關閉此次鏈接}}catch(IOExceptione){System.out.println(e);}}privateServerSocket
4、server=null;privatestaticfinalintPORT=5000;privateBufferedWriterwriter;privateBufferedReaderreader;privatevoidCreateSocket()throwsIOException{server=newServerSocket(PORT,100);System.out.println("Serverstarting..");}privateSocketResponseSocket()throwsIOException{Socketclient=server.accept();Sy
5、stem.out.println("clientconnected..");returnclient;}privatevoidCloseSocket(Socketsocket)throwsIOException{reader.close();writer.close();socket.close();System.out.println("clientclosed..");}privatevoidSendMsg(Socketsocket,StringMsg)throwsIOException{writer=newBufferedWriter(newOutputStreamWrit
6、er(socket.getOutputStream()));writer.write(Msg+"");writer.flush();}privateStringReceiveMsg(Socketsocket)throwsIOException{reader=newBufferedReader(newInputStreamReader(socket.getInputStream()));System.out.println("servergetinputfromclientsocket..");Stringtxt="Seversend:"+reader.readLine();r
7、eturntxt;}publicstaticvoidmain(finalStringargs[])throwsIOException{YaoChatServeryaochatserver=newYaoChatServer();if(yaochatserver!=null){yaochatserver.start();}}}Client端:packagecom.android.Yao;importjava.io.BufferedReader;importjava.io.Buffer