安卓手机socket通信(服务器和客户端)
本文实例为大家分享了安卓手机socket通信" title="socket通信">socket通信代码,供大家参考,具体内容如下
1、socket通信首先要定义好服务端的ip地址和端口号;
(1).首先看服务端的代码:
package com.example.androidsockettest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
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.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
public static ServerSocket serverSocket = null;
public static TextView mTextView, textView1;
private String IP = "";
String buffer = "";
public static Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
if (msg.what==0x11) {
Bundle bundle = msg.getData();
mTextView.append("client"+bundle.getString("msg")+"\n");
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textsss);
textView1 = (TextView) findViewById(R.id.textView1);
IP = getlocalip();
textView1.setText("IP addresss:"+IP);
new Thread() {
public void run() {
Bundle bundle = new Bundle();
bundle.clear();
OutputStream output;
String str = "通信成功";
try {
serverSocket = new ServerSocket(30000);
while (true) {
Message msg = new Message();
msg.what = 0x11;
try {
Socket socket = serverSocket.accept();
output = socket.getOutputStream();
output.write(str.getBytes("UTF-8"));
output.flush();
socket.shutdownOutput();
//mHandler.sendEmptyMessage(0);
BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
buffer = "";
while ((line = bff.readLine())!=null) {
buffer = line + buffer;
}
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
mHandler.sendMessage(msg);
bff.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
};
}.start();
}
private String getlocalip(){
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
// Log.d(Tag, "int ip "+ipAddress);
if(ipAddress==0)return null;
return ((ipAddress & 0xff)+"."+(ipAddress>>8 & 0xff)+"."
+(ipAddress>>16 & 0xff)+"."+(ipAddress>>24 & 0xff));
}
}
(2).因为是手机做服务端,所以在开始操作的时候客户端是不知道ip和端口号的,但在服务端运行后就可以看到(亲:你可以自己测试)
2、客户端的代码
package com.example.andoroidclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Socket socket = null;
String buffer = "";
TextView txt1;
Button send;
EditText ed1;
String geted1;
public Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x11) {
Bundle bundle = msg.getData();
txt1.append("server:" + bundle.getString("msg") + "\n");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.txt1);
send = (Button) findViewById(R.id.send);
ed1 = (EditText) findViewById(R.id.ed1);
new MyThread("建立连接").start();
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
geted1 = ed1.getText().toString();
txt1.append("client:" + geted1 + "\n");
// 启动线程 向服务器发送和接收信息
new MyThread(geted1).start();
}
});
}
class MyThread extends Thread {
public String txt1;
public MyThread(String str) {
txt1 = str;
}
@Override
public void run() {
// 定义消息
Message msg = new Message();
msg.what = 0x11;
Bundle bundle = new Bundle();
bundle.clear();
try {
// 连接服务器 并设置连接超时为5秒
socket = new Socket();
socket.connect(new InetSocketAddress("172.20.226.11", 30000), 1000);
// 获取输入输出流
OutputStream ou = socket.getOutputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 读取发来服务器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}
// 向服务器发送信息
ou.write(txt1.getBytes("gbk"));
ou.flush();
bundle.putString("msg", buffer.toString());
msg.setData(bundle);
// 发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
// 关闭各种输入输出流
bff.close();
ou.close();
socket.close();
} catch (SocketTimeoutException aa) {
// 连接超时 在UI界面显示消息
bundle.putString("msg", "服务器连接失败!请检查网络是否打开");
msg.setData(bundle);
// 发送消息 修改UI线程中的组件
myHandler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3、最后别忘记加网络权限
<uses-permission android:name="android.permission.INTERNET" />
源码下载:http://xiazai.jb51.net/201608/yuanma/android-socket(jb51.net).rar
以上是 安卓手机socket通信(服务器和客户端) 的全部内容, 来源链接: utcz.com/z/325358.html