Android基于socket实现的简单C/S聊天通信功能
程序员文章站
2024-03-04 09:03:17
本文实例讲述了android基于socket实现的简单c/s聊天通信功能。分享给大家供大家参考,具体如下:
主要想法:在客户端上发送一条信息,在后台开辟一个线程充当服务端...
本文实例讲述了android基于socket实现的简单c/s聊天通信功能。分享给大家供大家参考,具体如下:
主要想法:在客户端上发送一条信息,在后台开辟一个线程充当服务端,收到消息就立即回馈给客户端。
第一步:创建一个继续activity的socketclientactity类,包为com.pku.net
编写布局文件socketclient.xml,代码如下:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <scrollview android:id="@+id/scrollview3" android:layout_width="fill_parent" android:layout_height="wrap_content" > <textview android:id="@+id/chattxt2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#98f5ff" /> </scrollview> <edittext android:id="@+id/chattxt" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <button android:id="@+id/chatok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送" > </button> </linearlayout>
接下来编写socketclientactity.java文件:
package com.pku.net; import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.ioexception; import java.net.unknownhostexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.net.socket; import android.app.activity; import android.os.bundle; import android.view.view; import android.widget.*; public class socketclientactivity extends activity { socketserverthread yaochatserver; /** called when the activity is first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.socketclient); try { yaochatserver = new socketserverthread(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } if (yaochatserver != null) { yaochatserver.start(); } findviews(); setonclick(); } private edittext chattxt; private textview chattxt2; private button chatok; public void findviews() { chattxt = (edittext) this.findviewbyid(r.id.chattxt); chattxt2 = (textview) this.findviewbyid(r.id.chattxt2); chatok = (button) this.findviewbyid(r.id.chatok); } private void setonclick() { chatok.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { try { connecttoserver(chattxt.gettext().tostring()); } catch (unknownhostexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }); } public void connecttoserver(string socketdata) throws unknownhostexception, ioexception { socket socket = requestsocket("127.0.0.1", 5000); sendmsg(socket, socketdata); string txt = receivemsg(socket); this.chattxt2.settext(txt); } private socket requestsocket(string host, int port) throws unknownhostexception, ioexception { socket socket = new socket(host, port); return socket; } private void sendmsg(socket socket, string msg) throws ioexception { bufferedwriter writer = new bufferedwriter(new outputstreamwriter( socket.getoutputstream())); writer.write(msg.replace("\n", " ") + "\n"); writer.flush(); } private string receivemsg(socket socket) throws ioexception { bufferedreader reader = new bufferedreader(new inputstreamreader( socket.getinputstream())); string txt = reader.readline(); return txt; } }
编写androidmanifest.xml文件:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.pku.net" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" /> <uses-permission android:name="android.permission.internet"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".httpurlactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="getnetimage"></activity> <activity android:name="httpclientactivity"></activity> <activity android:name="socketclientactivity"></activity> </application> </manifest>
最后编写后台服务端的文件socketserverthread.java,代码如下:
package com.pku.net; import java.io.bufferedreader; import java.io.bufferedwriter; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstreamwriter; import java.net.serversocket; import java.net.socket; public class socketserverthread extends thread { public socketserverthread() throws ioexception { createsocket(); // 创建socket服务器 } public void run() { socket client; string txt; try { while (true) // 线程无限循环,实时监听socket端口 { client = responsesocket(); // 响应客户端链接请求。。 while (true) { txt = receivemsg(client); system.out.println(txt); // 链接获得客户端发来消息,并将其显示在server端的屏幕上 sendmsg(client, txt); // 向客户端返回消息 if (true) break; // 中断,继续等待链接请求 } closesocket(client); // 关闭此次链接 } } catch (ioexception e) { system.out.println(e); } } private serversocket server = null; private static final int port = 5000; private bufferedwriter writer; private bufferedreader reader; private void createsocket() throws ioexception { server = new serversocket(port, 100); system.out.println("server starting.."); } private socket responsesocket() throws ioexception { socket client = server.accept(); system.out.println("client connected.."); return client; } private void closesocket(socket socket) throws ioexception { reader.close(); writer.close(); socket.close(); system.out.println("client closed.."); } private void sendmsg(socket socket, string msg) throws ioexception { writer = new bufferedwriter(new outputstreamwriter( socket.getoutputstream())); writer.write(msg + "\n"); writer.flush(); } private string receivemsg(socket socket) throws ioexception { reader = new bufferedreader(new inputstreamreader( socket.getinputstream())); system.out.println("server get input from client socket.."); string txt = "sever send:" + reader.readline(); return txt; } /* public static void main(final string args[]) throws ioexception { socketserverthread yaochatserver = new socketserverthread(); if (yaochatserver != null) { yaochatserver.start(); } } */ }
运行效果如下图:
更多关于android相关内容感兴趣的读者可查看本站专题:《android通信方式总结》、《android开发入门与进阶教程》、《android调试技巧与常见问题解决方法汇总》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。
上一篇: 浅谈Java转义符\\|
下一篇: Asp.net防重复提交机制实现方法