您的位置:首页 > 移动开发 > Android开发

android实现socket连接(客户端)

2016-03-07 22:51 162 查看
学习socket通信,做了一个Demo,两台手机之间建立socket通信,今天先放出client端,欢迎大家交流。

public class MainActivity extends Activity {
EditText mIP;// 输入的IP
EditText mContent;// 发送内容
Button mBtn;// 发送按钮
Button mLogin;// 连接按钮
TextView mData;
private String ip = null;// IP地址
private int port = 8001;// 端口号
private Socket socket;
OutputStream output = null;// 输出流
DataInputStream inputStream;
String context = null;
Handler mHandler;
Handler handler;

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

mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0x100:
Toast.makeText(MainActivity.this, "已连接", Toast.LENGTH_SHORT).show();
break;
case 0x300:
Bundle bundle = msg.getData();
// 将十六进制字节显示为十六进制字符串
// mData.append(Bytes2HexString(bundle.getByteArray("byte"))+"\n");
//将字节数组显示为字符串
mData.append((bundle.getByteArray("byte"))+"\n");
// 将字符串显示出来
//mData.append(bundle.getString("byte") + "\n");
break;
default:
break;
}
}
};
}

private void init() {
mLogin.setOnClickListener(new BtnOnclick());
mBtn.setOnClickListener(new BtnOnclick());

}

class BtnOnclick implements OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.X_Login:
ip = mIP.getText().toString();// 获取输入的IP地址
if (ip != null) {
new Thread(new LoginThread()).start();// 新线程建立连接
new Thread(new DoThread()).start();// 新线程发送
} else {
Toast.makeText(getApplicationContext(), "请输入IP地址", Toast.LENGTH_SHORT).show();
}
break;
case R.id.X_SendBtn:
if (ip != null) {
mData.append(mContent.getText().toString()+"\n");
Bundle bundle = new Bundle();
Message message = Message.obtain();
// 获取发送的内容,传到子线程的输出流发送
bundle.putString("context", mContent.getText().toString());
message.setData(bundle);
handler.sendMessage(message);
} else {
Toast.makeText(getApplicationContext(), "请输入IP地址", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}

}

private void findview() {
mIP = (EditText) findViewById(R.id.X_IP_Edit);
mContent = (EditText) findViewById(R.id.X_Content_Edit);
mBtn = (Button) findViewById(R.id.X_SendBtn);
mLogin = (Button) findViewById(R.id.X_Login);
mData = (TextView) findViewById(R.id.X_data);
}

public class LoginThread implements Runnable {
@Override
public void run() {
try {
// 建立一个socket连接
socket = new Socket(ip, 8001);
// 获取输入流
inputStream = new DataInputStream(socket.getInputStream());
output = socket.getOutputStream();// 获取输出流
mHandler.sendEmptyMessage(0x100);// 提示已连接
while (true) {
try {// 此线程循环读取
byte[] buff = {};
Message msg1 = Message.obtain();
buff = new byte[inputStream.available()];
if (buff.length != 0) {// 如果不是十六位 的字节数组 打印出来
inputStream.read(buff);// 读取到缓存中
Bundle bundle = new Bundle();
// 1.传递字节数组 与UT8-8编码相同通信,
bundle.putByteArray("byte", buff);
// 2.传递字符串 与PC端通信需要把GBK转为UTF-8
//bundle.putString("byte", new String(buff, "gbk"));
msg1.setData(bundle);
msg1.what = 0x300;
mHandler.sendMessage(msg1);
}
} catch (IOException e) {
// 如果有异常发出此提示
mHandler.sendEmptyMessage(0x600);
}
}
} catch (IOException e) {
mHandler.sendEmptyMessage(0x200);
}
}
}

public class DoThread implements Runnable {
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
try {
//发送UTF-8编码
output.write(bundle.getString("context").getBytes("UTF-8"));
//发送GBK编码
//output.write(bundle.getString("context").getBytes("GBK"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Looper.loop();
}
}

private void CloseSocket() {
try {
inputStream.close();
output.close();// 关闭输出流
socket.close();// 关闭 socket
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private final static byte[] hex = "0123456789ABCDEF".getBytes();

public static String Bytes2HexString(byte[] b) {
byte[] buff = new byte[2 * b.length];
for (int i = 0; i < b.length; i++) {
buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
buff[2 * i + 1] = hex[b[i] & 0x0f];
}
return new String(buff);
}

@Override
protected void onDestroy() {
super.onDestroy();
CloseSocket();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: