Android基于socket实现的简单CS聊天通信功能

Android基于socket实现的简单CS聊天通信功能,第1张

概述本文实例讲述了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程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Android基于socket实现的简单C/S聊天通信功能全部内容,希望文章能够帮你解决Android基于socket实现的简单C/S聊天通信功能所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1149660.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存