/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.nsdchat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ChatConnection
{
private Handler mUpdateHandler;
private ChatServer mChatServer;
private ChatClient mChatClient;
private static final String TAG = "ChatConnection";
private Socket mSocket;
private int mPort = -1;
public ChatConnection(Handler handler)
{
mUpdateHandler = handler;
mChatServer = new ChatServer(handler);
}
public void tearDown()
{
mChatServer.tearDown();
mChatClient.tearDown();
}
public void connectToServer(InetAddress address, int port)
{
mChatClient = new ChatClient(address, port);
}
public void sendMessage(String msg)
{
if (mChatClient != null)
{
mChatClient.sendMessage(msg);
}
}
public int getLocalPort()
{
return mPort;
}
public void setLocalPort(int port)
{
mPort = port;
}
public synchronized void updateMessages(String msg, boolean local)
{
Log.e(TAG, "Updating message: " + msg);
if (local)
{
msg = "me: " + msg;
}
else
{
msg = "them: " + msg;
}
Bundle messageBundle = new Bundle();
messageBundle.putString("msg", msg);
Message message = new Message();
message.setData(messageBundle);
mUpdateHandler.sendMessage(message);
}
private synchronized void setSocket(Socket socket)
{
Log.d(TAG, "setSocket being called.");
if (socket == null)
{
Log.d(TAG, "Setting a null socket.");
}
if (mSocket != null)
{
if (mSocket.isConnected())
{
try
{
mSocket.close();
}
catch (IOException e)
{
// TODO(alexlucas): Auto-generated catch block
e.printStackTrace();
}
}
}
mSocket = socket;
}
private Socket getSocket()
{
return mSocket;
}
private class ChatServer
{
ServerSocket mServerSocket = null;
Thread mThread = null;
public ChatServer(Handler handler)
{
mThread = new Thread(new ServerThread());
mThread.start();
}
public void tearDown()
{
mThread.interrupt();
try
{
mServerSocket.close();
}
catch (IOException ioe)
{
Log.e(TAG, "Error when closing server socket.");
}
}
class ServerThread implements Runnable
{
@Override
public void run()
{
try
{
// Since discovery will happen via Nsd, we don't need to
// care which port is
// used. Just grab an available one and advertise it via
// Nsd.
mServerSocket = new ServerSocket(0);
setLocalPort(mServerSocket.getLocalPort());
while (!Thread.currentThread().isInterrupted())
{
Log.d(TAG, "ServerSocket Created, awaiting connection");
setSocket(mServerSocket.accept());
Log.d(TAG, "Connected.");
if (mChatClient == null)
{
int port = mSocket.getPort();
InetAddress address = mSocket.getInetAddress();
connectToServer(address, port);
}
}
}
catch (IOException e)
{
Log.e(TAG, "Error creating ServerSocket: ", e);
e.printStackTrace();
}
}
}
}
private class ChatClient
{
private InetAddress mAddress;
private int PORT;
private final String CLIENT_TAG = "ChatClient";
private Thread mSendThread;
private Thread mRecThread;
public ChatClient(InetAddress address, int port)
{
Log.d(CLIENT_TAG, "Creating chatClient");
this.mAddress = address;
this.PORT = port;
mSendThread = new Thread(new SendingThread());
mSendThread.start();
}
class SendingThread implements Runnable
{
BlockingQueue<String> mMessageQueue;
private int QUEUE_CAPACITY = 10;
public SendingThread()
{
mMessageQueue = new ArrayBlockingQueue<String>(QUEUE_CAPACITY);
}
@Override
public void run()
{
try
{
if (getSocket() == null)
{
setSocket(new Socket(mAddress, PORT));
Log.d(CLIENT_TAG, "Client-side socket initialized.");
}
else
{
Log.d(CLIENT_TAG,
"Socket already initialized. skipping!");
}
mRecThread = new Thread(new ReceivingThread());
mRecThread.start();
}
catch (UnknownHostException e)
{
Log.d(CLIENT_TAG, "Initializing socket failed, UHE", e);
}
catch (IOException e)
{
Log.d(CLIENT_TAG, "Initializing socket failed, IOE.", e);
}
while (true)
{
try
{
String msg = mMessageQueue.take();
sendMessage(msg);
}
catch (InterruptedException ie)
{
Log.d(CLIENT_TAG,
"Message sending loop interrupted, exiting");
}
}
}
}
class ReceivingThread implements Runnable
{
@Override
public void run()
{
BufferedReader input;
try
{
input = new BufferedReader(new InputStreamReader(
mSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted())
{
String messageStr = null;
messageStr = input.readLine();
if (messageStr != null)
{
Log.d(CLIENT_TAG, "Read from the stream: "
+ messageStr);
updateMessages(messageStr, false);
}
else
{
Log.d(CLIENT_TAG, "The nulls! The nulls!");
break;
}
}
input.close();
}
catch (IOException e)
{
Log.e(CLIENT_TAG, "Server loop error: ", e);
}
}
}
public void tearDown()
{
try
{
getSocket().close();
}
catch (IOException ioe)
{
Log.e(CLIENT_TAG, "Error when closing server socket.");
}
}
public void sendMessage(String msg)
{
try
{
Socket socket = getSocket();
if (socket == null)
{
Log.d(CLIENT_TAG, "Socket is null, wtf?");
}
else if (socket.getOutputStream() == null)
{
Log.d(CLIENT_TAG, "Socket output stream is null, wtf?");
}
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(getSocket().getOutputStream())),
true);
out.println(msg);
out.flush();
updateMessages(msg, true);
}
catch (UnknownHostException e)
{
Log.d(CLIENT_TAG, "Unknown Host", e);
}
catch (IOException e)
{
Log.d(CLIENT_TAG, "I/O Exception", e);
}
catch (Exception e)
{
Log.d(CLIENT_TAG, "Error3", e);
}
Log.d(CLIENT_TAG, "Client sent message: " + msg);
}
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
NsdChat工程源码
共40个文件
class:19个
java:5个
xml:5个
1星 需积分: 10 14 下载量 120 浏览量
2015-08-06
10:53:19
上传
评论
收藏 70KB ZIP 举报
温馨提示
作者:【郭孝星】http://blog.csdn.net/allenwells 微博:【郭孝星的新浪微博】http://weibo.com/allenwells 邮箱:allenwells@163.com 博客:http://blog.csdn.net/allenwells Github:https://github.com/AllenWells
资源推荐
资源详情
资源评论
收起资源包目录
NsdChat.zip (40个子文件)
NsdChat
bin
res
classes
com
example
android
nsdchat
BuildConfig.class 363B
NsdChatActivity.class 3KB
ChatConnection$ChatClient.class 4KB
NsdHelper$1.class 3KB
ChatConnection$ChatServer$ServerThread.class 2KB
R$layout.class 421B
R$id.class 584B
R$drawable.class 434B
ChatConnection$ChatServer.class 2KB
ChatConnection.class 4KB
NsdChatActivity$1.class 1KB
R$attr.class 367B
NsdHelper.class 3KB
R.class 594B
NsdHelper$2.class 2KB
R$string.class 548B
ChatConnection$ChatClient$SendingThread.class 3KB
ChatConnection$ChatClient$ReceivingThread.class 2KB
NsdHelper$3.class 1KB
AndroidManifest.xml 1KB
res
drawable-ldpi
ic_launcher.png 3KB
drawable-hdpi
ic_launcher.png 9KB
drawable-xhdpi
ic_launcher.png 14KB
values
strings.xml 896B
drawable-mdpi
ic_launcher.png 5KB
layout
main.xml 2KB
build.xml 4KB
assets
gen
com
example
android
nsdchat
BuildConfig.java 169B
R.java 1KB
proguard.cfg 910B
Android.mk 411B
.settings
org.eclipse.jdt.core.prefs 177B
src
com
example
android
nsdchat
NsdHelper.java 5KB
NsdChatActivity.java 3KB
ChatConnection.java 7KB
.project 845B
.classpath 475B
local.properties 438B
project.properties 563B
AndroidManifest.xml 1KB
libs
共 40 条
- 1
资源评论
- 菜的一批2017-02-14崩了,不能用
郭孝星
- 粉丝: 306
- 资源: 28
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功