安卓编程实现wifi聊天,视频和音频通话
安卓编程实现wifi聊天,传文件,视频和音频通话
在移动开发的过程中,即时通讯是许多app必须要用到的功能,许多app都没有自主开发自己的聊天系统,反而引用了第三方的即时通讯sdk,贵还不说,有时候想自己增加功能也是麻烦,本文通过安卓编程为例,使用wifi作为服务器,实现了安卓即时通讯和视频音频的通话功能。
安卓开启热点服务
安卓系统自带的热点服务,本次编程将热点开启作为局域网的聊天服务器,一台手机作为主服务器搭建聊天服务。
热点创建服务代码如下
public void createServer(){
try {
// System.out.println(“本机ip:”+getLocalIpAddress());
ServerSocket ss = new ServerSocket(30000);
while (true) {
String localip= getHostIP();
System.out.println("本机ip:"+localip);
Socket s = ss.accept();
System.out.println("已连接ip:"+s.getInetAddress().toString());
vibrators();
// showNot(“已连接ip:”+s.getInetAddress().toString());
simpleNotice(“已连接ip:”+s.getInetAddress().toString());
socketList.add(s);
new Thread(new ServerThead(s,handler)).start();
Intent intent = new Intent();
intent.setAction("www.ailiaw.com.mywifi");//设置意图
intent.putExtra("action", "newmsg");//设置所需发送的消息标签以及内容
// BroadCastActivity.this.sendBroadcast(intent);
SimpleServer.this.sendOrderedBroadcast(intent,null);//有序广播
}
} catch (IOException e) {
e.printStackTrace();
}
}
客户端也是由安卓手机来接受的,使用普通的Socket连接即可
public void createConnection() {
try {
socket = new Socket(ip, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (socket != null) {
try {
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (socket != null) {
try {
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} finally {
}
}
Socket客户端发送文本消息方法
public void sendMessage(String sendMessage) {
try {
out = new DataOutputStream(socket.getOutputStream());
if (sendMessage.equals(“Windows”)) {
out.w