一: 主要功能
实现多手机在同一局域网互相通信
二:客户端主要代码
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.app.Activity;
import android.app.Instrumentation;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MinaClientActivity extends Activity implements View.OnClickListener {
private Socket mClientSocket;
private String mSendContent;
private TextView mTvConnectServer;
private Button mBtnSend;
private EditText mEtSendContent;
private EditText mEtInputIp;
private ConnectServerThread mConnectServerThread;
private SendMsgServerThread mSendMsgServerThread;
private PrintWriter mPrintWriterOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mina_server);
mTvConnectServer = (TextView) findViewById(R.id.tv_connect_server);
mBtnSend = (Button) findViewById(R.id.bt_send);
mEtSendContent = (EditText) findViewById(R.id.et_send_message);
mEtInputIp = (EditText) findViewById(R.id.et_input_ip);
mBtnSend.setOnClickListener(this);
mTvConnectServer.setOnClickListener(this);
mConnectServerThread = new ConnectServerThread();
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
//发送消息
case R.id.bt_send:
Toast.makeText(this,"send click",Toast.LENGTH_SHORT).show();
mSendMsgServerThread = new SendMsgServerThread();
Thread sendThread = new Thread(mSendMsgServerThread);
sendThread.start();
// sendKeyEvent(KeyEvent.KEYCODE_BACK);
break;
//连接server
case R.id.tv_connect_server:
Toast.makeText(this,"connect click",Toast.LENGTH_SHORT).show();
Thread connectThread = new Thread(mConnectServerThread);
connectThread.start();
break;
}
}
private class ConnectServerThread implements Runnable {
@Override
public void run() {
try {
String ip = mEtInputIp.getText().toString().replaceAll(" ","");
mClientSocket = new Socket();
mClientSocket.connect(new InetSocketAddress(ip, 30000), 1000);
} catch (SocketTimeoutException e) {
MyLog.logD("ConnectServerThread SocketTimeoutException");
} catch (IOException e) {
MyLog.logD("ConnectServerThread IOException" + e.toString());
}
MyLog.logD("ConnectServerThread mClientSocket.isConnected() " + mClientSocket.isConnected());
}
}
private class SendMsgServerThread implements Runnable{
@Override
public void run() {
try {
//输出
mPrintWriterOut = new PrintWriter ( mClientSocket.getOutputStream());
String sendMsg = mEtSendContent.getText().toString().replaceAll(" ","");
mPrintWriterOut.write(sendMsg);
mPrintWriterOut.flush();
} catch (SocketTimeoutException e) {
MyLog.logD("sendMessageToServer SocketTimeoutException");
} catch (IOException e) {
MyLog.logD("sendMessageToServer IOException");
}
}
}
}
对应的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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入IP"
android:padding="10dp"
android:ems="10"
android:layout_margin="10dp"
android:background="#fa870a"
android:id="@+id/et_input_ip" />
<TextView
android:id="@+id/tv_connect_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#ffffff"
android:background="#fa870a"
android:layout_margin="10dp"
android:text="连接server"
android:padding="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="发送的内容"
android:padding="10dp"
android:layout_margin="10dp"
android:background="#fa870a"
android:ems="10"
android:id="@+id/et_send_message" />
<Button
android:id="@+id/bt_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textColor="#ffffff"
android:background="#fa870a"
android:layout_margin="10dp"
android:text="发送"/>
</LinearLayout>
三: Server端主要代码
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import android.app.Instrumentation;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.view.KeyEvent;
import android.widget.TextView;
public class AsLearningMainActivity extends Activity {
public static TextView mTvReceiveMsg;
public static TextView mTvIp;
private InterActionClientThread mInterActionClientThread;
private InputStream mClientSocketIn;
private String mReceiveMsg = "";
private int mUpdateReceiveMsgWhat = 0x11;
private HashMap<String,String> mKeyMap = new HashMap<String,String>();
public Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
if(msg.what == mUpdateReceiveMsgWhat){
String receiveMsg = msg.obj.toString();
mTvReceiveMsg.setText(receiveMsg);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_as_learning_main);
mTvReceiveMsg = (TextView) findViewById(R.id.tv_receive_msg);
mTvIp = (TextView) findViewById(R.id.tv_ip);
String ip = getlocalip();
mTvIp.setText("IP addresss:" + ip);
mInterActionClientThread = new InterActionClientThread();
Thread sendThread = new Thread(mInterActionClientThread);
sendThread.start();
}
/**
* 或取本机的ip地址
*/
private String getlocalip() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
if (ipAddress == 0) return null;
return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
+ (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
}
private class InterActionClientThread implements Runnable{
@Override
public void run() {
try {
ServerSocket mServerSocket = new ServerSocket(30000);
while (true)
{
//accept是阻塞的 因此该方法只有当有连接的时候才继续执行
Socket socket = mServerSocket.accept();
mClientSocketIn = socket.getInputStream();
MyLog.logD("InterActionClientThread socket.isConnected() " + socket.isConnected() + " " + socket.getInetAddress().toString());
byte[] bt = new byte[10];
mClientSocketIn.read(bt);
mReceiveMsg = new String(bt,"UTF-8");
MyLog.logD("InterActionClientThread mReceiveMsg " + mReceiveMsg);
if (mReceiveMsg != null && mReceiveMsg != "exit")
{
Message msg = new Message();
msg.what = mUpdateReceiveMsgWhat;
msg.obj = mReceiveMsg + socket.getInetAddress().toString();
mHandler.sendMessage(msg);
sendKeyEvent(KeyEvent.KEYCODE_BACK);
}else if (mReceiveMsg == null || mReceiveMsg == "exit"){
break;
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
MyLog.logD("InterActionClientThread IOException");
}
}
}
public void sendKeyEvent(int keycode){
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(keycode);
}
}
主要的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_as_learning_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.migu.hwj.as.learning.server.AsLearningMainActivity">
<TextView
android:id="@+id/tv_receive_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="接收到的信息:" />
<TextView
android:id="@+id/tv_ip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="本机IP地址" />
</LinearLayout>
本文介绍了一种基于Android平台的局域网内多手机互相通信的实现方案。客户端通过Socket连接服务器,并发送消息;服务器端接收消息并显示。涉及的技术包括Socket编程、线程处理及UI更新。
1554

被折叠的 条评论
为什么被折叠?



