欢迎来到天天文库
浏览记录
ID:41033475
大小:68.50 KB
页数:7页
时间:2019-08-14
《以聊天为例讲解关于Android_的socket编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、关于Android的socket编程【以聊天为例】下面,用敲门的方式演示Android如何实现套接字的通信。本例实现功能如下:Server端开启服务Client端发起链接请求,并向Server端发送数据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();//创建Socket服务器}publicvoidrun(){Socketclient;Stringtxt;try{while(true)//线程无限循
3、环,实时监听socket端口{client=ResponseSocket();//响应客户端链接请求。。while(true){txt=ReceiveMsg(client);System.out.println(txt);//链接获得客户端发来消息,并将其显示在Server端的屏幕上SendMsg(client,txt);//向客户端返回消息if(true)break;//中断,继续等待链接请求}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
此文档下载收益归作者所有