Android聊天工具基于socket实现

特简单, 没有数据库, 还没有处理各种异常。
登录:输入用户名点击的登录即可。
发送消息: 特定格式->toUser:message
1. 服务器:保存在线用户

public class Online {
 private static Online mOnline = null;
 private LinkedHashMap<String, Socket> mOnlines = new LinkedHashMap<String, Socket>();

 private Online() {
 }

 public synchronized static Online getInstance() {
  if(null == mOnline) {
   mOnline = new Online();
  }

  return mOnline;
 }

 public void put(String key, Socket socket) {
  if(!mOnlines.containsKey(key)) {
   mOnlines.put(key, socket);
  }
 }

 public Socket get(String key) {
  return mOnlines.get(key);
 }

 public void remove(String key) {
  mOnlines.remove(key);
 }
}

2. 服务器:一个简单的socket服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

// login:uid
// send:fromuser:touser:message
// logout:uid
public class Server implements Runnable {
 private Socket mSocket;
 private Online mOnline;

 public Server(Socket socket) {
  mSocket = socket;
  mOnline = Online.getInstance();
 }

 @Override
 public void run() {
  try {
   BufferedReader reader = new BufferedReader(new InputStreamReader(
     mSocket.getInputStream()));
   String cmd = reader.readLine();

   // login
   if (cmd.startsWith("login")) {
    String userName = cmd.split(":")[1];
    mOnline.put(userName, mSocket);
    System.out.println(userName + " login...");

    PrintWriter writer = new PrintWriter(mSocket.getOutputStream());
    writer.println("success");
    writer.flush();
   } else if (cmd.startsWith("send")) {
    System.out.println(cmd);
    String[] cmds = cmd.split(":");
    String from = cmds[1];
    Socket to = mOnline.get(cmds[2]);
    String msg = cmds[3];

    PrintWriter writer = new PrintWriter(to.getOutputStream());
    System.out.println("rec:" + from + ":" + cmds[2] + ":" + msg);

    writer.println("rec:" + from + ":" + cmds[2] + ":" + msg);
    writer.flush();
   }else if (cmd.startsWith("logout")) {
    System.out.println(cmd);

    String user = cmd.split(":")[1];
    mOnline.get(user).close();
    mOnline.remove(user);

    PrintWriter writer = new PrintWriter(mSocket.getOutputStream());
    writer.println("success");
    writer.flush();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String[] args) throws Exception {
  ServerSocket server = new ServerSocket(8888);
  boolean flag = true;
  while (flag) {
   new Thread(new Server(server.accept())).start();
   System.out.println("user in...");
  }

  server.close();
 }
}

3. 客户端登录界面

public class MainActivity extends Activity {
 private EditText mUser;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mUser = (EditText) findViewById(R.id.username);
 }

 public void login(View view) {
  final String userName = mUser.getText().toString().trim();
  Login login = new Login(userName);
  login.setOnLoginListener(new Login.LoginCallback() {
   @Override
   public void onLogin(boolean success) {
    if(success) {
     Intent intent = new Intent(MainActivity.this, Chat.class);
     intent.putExtra("user", userName);
     startActivity(intent);
     finish();
    }else {
     Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
    }
   }
  });

  login.login();
 }
}

4. 处理登录

public class Login {
 private String mUserName;
 private LoginCallback mCallback;

 public Login(String userName) {
  mUserName = userName;
 }

 public void setOnLoginListener(LoginCallback callback) {
  mCallback = callback;
 }

 private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case Constant.SUCCESS:
    mCallback.onLogin(true);
    break;
   case Constant.FAILED:
    mCallback.onLogin(false);
    break;
   }
  };
 };

 public void login() {
  new Thread(new Runnable() {
   @Override
   public void run() {
    Socket socket = null;
    try {
     socket = new Socket();
     socket.connect(new InetSocketAddress("192.168.100.100", 8888), 4000);
     PrintWriter writer = new PrintWriter(socket.getOutputStream());
     writer.println("login:" + mUserName);
     writer.flush();

     BufferedReader reader = new BufferedReader(
       new InputStreamReader(socket.getInputStream()));
     String line = reader.readLine();
     System.out.println(line);
     if("success".equals(line)) {
      PConnection.socket = socket;
      mHandler.sendEmptyMessage(Constant.SUCCESS);
     }else {
      mHandler.sendEmptyMessage(Constant.FAILED);
     }
    }catch(Exception e) {
     e.printStackTrace();
    }
   }
  }).start();
 }

 public interface LoginCallback {
  public void onLogin(boolean success);
 }
}

5. 聊天界面

public class Chat extends Activity {
 private String mUserName;
 private EditText mEdit;
 private ListView mMessage;

 private ReceiverMessage mRecMessage;
 private SendMessage mSendMesage;
 private List<Map<String, String>> mData = new ArrayList<Map<String, String>>();
 private MessagesAdapter mAdapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.chat_layout);

  mUserName = getIntent().getStringExtra("user");
  mEdit = (EditText) findViewById(R.id.edit);
  mMessage = (ListView) findViewById(R.id.message);

  mRecMessage = new ReceiverMessage();
  mRecMessage.setOnReceiverListener(new RecListener());
  mRecMessage.run();

  mSendMesage = new SendMessage();
  mSendMesage.setOnSendListener(new SendListener());

  mAdapter = new MessagesAdapter(this, mData);
  mMessage.setAdapter(mAdapter);
 }

 public void send(View view) {
  String[] content = mEdit.getText().toString().trim().split(":");
  mSendMesage.send(mUserName, content[0], content[1]);
 }

 private class RecListener implements ReceiverMessage.OnReceiverListener {
  @Override
  public void onReceiver(String user, String msg) {
   Map<String, String> temp = new HashMap<String, String>();
   temp.put("user", user);
   temp.put("msg", msg);
   temp.put("pos", "right");
   mData.add(temp);
   mAdapter.notifyDataSetChanged();
  }
 }

 private class SendListener implements SendMessage.OnSendListener {
  @Override
  public void onSend(String[] msg) {
   Map<String, String> temp = new HashMap<String, String>();
   temp.put("user", "我");
   temp.put("msg", msg[1]);
   temp.put("pos", "left");
   mData.add(temp);
   mAdapter.notifyDataSetChanged();
  }
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  if(R.id.logout == item.getItemId()) {
   Logout logout = new Logout();
   logout.setOnLogoutListener(new Logout.OnLogoutListener() {
    @Override
    public void onLogout(boolean success) {
     if(success) {
      Toast.makeText(Chat.this, "注销成功", Toast.LENGTH_SHORT).show();
      finish();
     }else {
      Toast.makeText(Chat.this, "注销失败", Toast.LENGTH_SHORT).show();
     }
    }
   });

   logout.logout(mUserName);
  }

  return super.onOptionsItemSelected(item);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return super.onCreateOptionsMenu(menu);
 }
}

6. 发送消息

public class SendMessage {
 private OnSendListener mListener;

 public void setOnSendListener(OnSendListener listener) {
  mListener = listener;
 }

 private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   mListener.onSend((String[]) msg.obj);
  };
 };

 // send:from:to:message
 public void send(final String from , final String to, final String msg) {
  new Thread(new Runnable() {
   @Override
   public void run() {
    Socket socket = null;
    try {
     socket = new Socket();
     socket.connect(new InetSocketAddress("192.168.100.100", 8888), 4000);
     PrintWriter writer = new PrintWriter(socket.getOutputStream());
     writer.println("send:" + from + ":" + to + ":" + msg);
     writer.flush();

     Message message = mHandler.obtainMessage(
       Constant.SUCCESS, new String[] {to, msg});

     message.sendToTarget();
    } catch(Exception e) {
    } finally {
     try {
      socket.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
  }).start();
 }

 public interface OnSendListener {
  public void onSend(String[] msg);
 }
}

7. 接收消息,死循环,但阻塞,没啥问题

public class ReceiverMessage {
 private OnReceiverListener mListener;
 public void setOnReceiverListener(OnReceiverListener listener) {
  mListener = listener;
 }

 private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   String[] cmds = (String[]) msg.obj;
   mListener.onReceiver(cmds[0], cmds[1]);
  };
 };

 public void run() {
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     Socket socket = PConnection.socket;
     while(true) {
      System.out.println("wait for message...");
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(socket.getInputStream()));
      String line = reader.readLine();

      if(line.startsWith("rec")) {
       //rec:fromuser:touser:message
       String[] cmds = line.split(":");
       System.out.println(cmds[0] + ":" + cmds[1] + ":" + cmds[2] + ":" + cmds[3]);
       Message msg = mHandler.obtainMessage(Constant.SUCCESS, new String[] {cmds[1], cmds[3]});
       msg.sendToTarget();
      }
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }).start();
 }

 public interface OnReceiverListener {
  public void onReceiver(String user, String msg);
 }
}

8. 注销登录

public class Logout {
 public OnLogoutListener mListener;

 public void setOnLogoutListener(OnLogoutListener listner) {
  mListener = listner;
 }

 private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   if(Constant.SUCCESS == msg.what) {
    mListener.onLogout(true);
   }else {
    mListener.onLogout(false);
   }
  };
 };

 public void logout(final String user) {
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     Socket socket = new Socket();
     socket.connect(new InetSocketAddress("192.168.100.100", 8888), 4000);
     PrintWriter writer = new PrintWriter(socket.getOutputStream());
     writer.println("logout:" + user);
     writer.flush();

     BufferedReader reader = new BufferedReader(
       new InputStreamReader(socket.getInputStream()));

     if("success".equals(reader.readLine())) {
      PConnection.socket = null;
      mHandler.sendEmptyMessage(Constant.SUCCESS);
     }else {
      mHandler.sendEmptyMessage(Constant.FAILED);
     }
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }).start();
 }

 public interface OnLogoutListener {
  public void onLogout(boolean success);
 }
}

9. 存放登录后的socket,在发送消息和接收消息时使用该socket

public class PConnection {
 public static Socket socket;
}

希望本文所述对大家学习有所帮助。

(0)

相关推荐

  • Android基于socket实现的简单C/S聊天通信功能

    本文实例讲述了Android基于socket实现的简单C/S聊天通信功能.分享给大家供大家参考,具体如下: 主要想法:在客户端上发送一条信息,在后台开辟一个线程充当服务端,收到消息就立即回馈给客户端. 第一步:创建一个继续Activity的SocketClientActity类,包为com.pku.net 编写布局文件socketclient.xml,代码如下: <?xml version="1.0" encoding="utf-8"?> <Lin

  • android socket聊天室功能实现

    前提概要 笔者很久之前其实就已经学习过了socket,当然也是用socket做过了聊天室,但是觉得此知识点比较一般,并无特别难的技术点,于是也并未深究. 然而近期一个项目中对socket的使用却让笔者感觉socket强大无比,可以实现诸多功能. 个人Socket体验 项目主要有关智能家居,需要实现多台手机同时对灯进行操作(开或者关),主要需要实现以下几点: 1.进入界面时获取所有灯的状态. 2.一台手机改变了灯的状态,其他的手机上可以有所显示. 3.硬件上改变了灯的状态(手动开关灯),所有手机上

  • 基于Socket.IO实现Android聊天功能代码示例

    一.简述 Socket.IO是一个完全由JavaScript实现.基于Node.js.支持WebSocket的协议用于实时通信.跨平台的开源框架,它包括了客户端的JavaScript和服务器端的Node.js. 该种官方介绍看起来有点懵逼,简而言之就是:客户端可通过Socket.IO与服务器建立实时通信管道 二.应用 该下就是介绍Socket.IO通信管道的铺设.通信以及销毁工作. 2.1 引入Socket.io包 compile 'io.socket:socket.io-client:0.8.

  • Android 基于Socket的聊天室实例

    Socket是TCP/IP协议上的一种通信,在通信的两端各建立一个Socket,从而在通信的两端之间形成网络虚拟链路.一旦建立了虚拟的网络链路,两端的程序就可以通过虚拟链路进行通信. Client A  发信息给 Client B ,  A的信息首先发送信息到服务器Server ,Server接受到信息后再把A的信息广播发送给所有的Clients 首先我们要在服务器建立一个ServerSocket ,ServerSocket对象用于监听来自客户端的Socket连接,如果没有连接,它将一直处于等待

  • Android 基于Socket的聊天应用实例(二)

    前言 很久没写BLOG了,之前在写Android聊天室的时候答应过要写一个客户(好友)之间的聊天demo,Android 基于Socket的聊天室已经实现了通过Socket广播形式的通信功能. 以下是我写的一个类似现在多数聊天软件的冒泡聊天APP.全部功能都是自己的想法,对于现在市面上成功的例子是怎么实现的,我还不了解.所以读者可只做参考学习,也可以分享您的案例给我. 功能 一对一聊天,非聊天室 好友列表 好友在线,离线状态(实时更新) 冒泡实时聊天窗口 发送离线信息 基本原理 之前的聊天室原理

  • android Socket实现简单聊天小程序

    android Socket实现简单聊天小程序,供大家参考,具体内容如下 服务器端: package org.hwq.echo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public cla

  • android Socket实现简单聊天功能以及文件传输

    干程序是一件枯燥重复的事,每当感到内心浮躁的时候,我就会找小说来看.我从小就喜爱看武侠小说,一直有着武侠梦.从金庸,古龙,梁羽生系列到凤歌(昆仑),孙晓(英雄志)以及萧鼎的(诛仙)让我领略着不一样的江湖. 如果你有好看的武侠系列小说,给我留言哦.题外话就扯这么多了,接着还是上技术. 看看今天实现的功能效果图: 可以这里使用多台手机进行通讯,我采用的服务器发送消息. 是不是只有发送消息,有些显得太单调了.好,在发送消息的基础上增加文件传输.后期会增加视频,音频的传输,增加表情包.那一起来看看图文消

  • Android聊天工具基于socket实现

    特简单, 没有数据库, 还没有处理各种异常. 登录:输入用户名点击的登录即可. 发送消息: 特定格式->toUser:message 1. 服务器:保存在线用户 public class Online { private static Online mOnline = null; private LinkedHashMap<String, Socket> mOnlines = new LinkedHashMap<String, Socket>(); private Onlin

  • Python基于Socket实现的简单聊天程序示例

    本文实例讲述了Python基于Socket实现的简单聊天程序.分享给大家供大家参考,具体如下: 需求:SCIENCE 和MOOD两个人软件专业出身,厌倦了大众化的聊天软件,想着自己开发一款简易的聊天软件,满足他们的个性化需求,又不失"专业水准",Talk is easy, try to code it. 技术:socket,详细可参考前文:Python Socket实现简单TCP Server/client功能 语言:python 尽管socket区分服务器和客户端,但是在聊天程序中两

  • Java基于socket实现简易聊天室实例

    本文实例讲述了Java基于socket实现简易聊天室的方法.分享给大家供大家参考.具体实现方法如下: chatroomdemo.java package com.socket.demo; import java.io.IOException; import java.net.DatagramSocket; public class ChatRoomDemo { /** * @param args * @throws IOException */ public static void main(S

  • 基于socket和javaFX简单文件传输工具

    本文实例介绍了基于socket和javaFX简单文件传输工具,分享给大家供大家参考,具体内容如下 package application; import java.io.File; import org.james.component.ButtonBox; import org.james.component.FileReceiverGrid; import org.james.component.FileSenderGrid; import javafx.application.Applica

  • java Socket简易聊天工具

    本文实例为大家分享了一款Socket简易聊天工具,希望大家喜欢. 代码运行如图,看起来还不错 服务端 package qiu; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.Printable; import java.io.BufferedReader; import java.io.IOEx

  • Android编程实现基于局域网udp广播自动建立socket连接的方法

    本文实例讲述了Android编程实现基于局域网udp广播自动建立socket连接的方法.分享给大家供大家参考,具体如下: android开发中经常会用到socket通讯.由于项目需要,最近研究了一下这方面的知识. 需求是想通过wifi实现android移动设备和android平台的电视之间的文件传输与控制. 毫无疑问这中间一定需要用到socket来进行通信.今天就两台设备的握手连接方式分享一下吧,该方法只是本人个人想法的实现,仅供参考,如有雷同,不胜荣幸. 要想使用socket进行通讯,就必须知

  • Python基于Socket实现简单聊天室

    本文实例为大家分享了Python基于Socket实现简单聊天室,供大家参考,具体内容如下 服务端 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/27 15:34 # @File : Server.py """ 聊天室服务端 """ import socket,select host='' port=7799 addr=(host,port) inputs=[] mem

随机推荐