安卓手机安卓手机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")+"");
}
};
};
@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();