android 使用TCP通信demo

1 android客户端

package com.test;



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.Socket;
import java.net.UnknownHostException;


import org.apache.commons.lang3.StringUtils;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
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 MySocketActivity extends Activity {
public static final String bm = "utf-8"; // 全局定义,以适应系统其他部分
private Button button;
private MyHandler myHandler;
private EditText sendMsg;
private TextView receiveMsg;
private ProgressDialog progressDialog;


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysocket_main);


button = (Button) findViewById(R.id.button1);
sendMsg = (EditText) findViewById(R.id.send_socket);


button.setOnClickListener(listener);
}


/**

*/
private OnClickListener listener = new OnClickListener() {


@Override
public void onClick(View v) {
String sendSocketMsg = sendMsg.getText().toString().trim();
if (StringUtils.isBlank(sendSocketMsg)) {
Toast.makeText(MySocketActivity.this, "消息内容为空",
Toast.LENGTH_LONG).show();
sendMsg.requestFocus();
return;
}


receiveMsg = (TextView) findViewById(R.id.receivesocketTextView);
MySocketActivity.this.receiveMsg.setText(null); // 把Textview清空


progressDialog = ProgressDialog.show(MySocketActivity.this, "提示",
"正在查询,请稍等……", true, true);


myHandler = new MyHandler();


MyThread m = new MyThread();
new Thread(m).start();
}


};


/**
* 接受消息,处理消息 ,此Handler会与当前主线程一块运行
* */


@SuppressLint("HandlerLeak")
class MyHandler extends Handler {
public MyHandler() {
}


public MyHandler(Looper L) {
super(L);
}


// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
Log.d("MyHandler", "handleMessage......");


// 关闭ProgressDialog
if (progressDialog != null) {
progressDialog.dismiss();
}


super.handleMessage(msg);


// 此处可以更新UI
Bundle b = msg.getData();


String receivemessage = b.getString("receivemessage");


MySocketActivity.this.receiveMsg.append(receivemessage);


}
}


/**

* @Description:
* @author wxg
* @Date:2013-10-15

*/
class MyThread implements Runnable {


@Override
public void run() {
Log.d("thread.......", "mThread........");


// 发送socket请求
String sendmessage = sendMsg.getText().toString().trim();
String inmsg = doSocketConnect(sendmessage);


Bundle b = new Bundle();// 存放数据
b.putString("receivemessage", inmsg);


Message msg = new Message();
msg.setData(b);
MySocketActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
}
}


/**
* socket通信

* @param sendmessage
* @return
*/
private String doSocketConnect(String sendmessage) {
try {
// 初始化Socket,TCP_SERVER_PORT为指定的端口,int类型
int TCP_SERVER_PORT = 8888;
Socket socket = new Socket("192.168.1.183", TCP_SERVER_PORT);
// 获取输入流
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));


// 生成输出流
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream(), "GBK")), true);


sendmessage = "你好" + sendmessage + "END";


// 生成输出内容
String outMsg = sendmessage + System.getProperty("line.separator");


// 写入
out.write(outMsg);
// 刷新,发送
out.flush();
// 获取输入流
String inMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpClient", "received: " + inMsg);
// 关闭连接
socket.close();


return inMsg;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


}


=============服务端

package com.sls.test.log.socket;


import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyAndroidServerSocket {
//创建一个线程池
private ExecutorService mExecutorService = null; //thread pool 


/**
* @param args
*/
public static void main(String[] args) {
MyAndroidServerSocket my = new MyAndroidServerSocket();
my.doServerSocket();


}


private void doServerSocket() {
ServerSocket serverSocket = null;
try {
// TCP_SERVER_PORT为指定的绑定端口,为int类型
serverSocket = new ServerSocket(8888);
//创建一个线程池
mExecutorService = Executors.newCachedThreadPool();  //create a thread pool 
while (true) {
System.out.println("ServerSocket Start:" + serverSocket);
// 监听连接请求
Socket client = serverSocket.accept();// 监听
ChildTh child = new ChildTh(client);
mExecutorService.execute(child); //利用线程池
// Thread t = new Thread(child);
// t.start();
}
} catch (Exception e) {
e.printStackTrace();
}


}


}


===============

package com.sls.test.log.socket;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class ChildTh implements Runnable {
public static final String bm = "utf-8"; //全局定义,以适应系统其他部分 
private Socket client;


public ChildTh(Socket client) {
this.client = client;
}


public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
//client.getOutputStream()
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(   
client.getOutputStream(),bm)), true);
while (true) {
// 读取接收信息,转换为字符串
String incomingMsg = in.readLine();
String endMSg = incomingMsg.substring(incomingMsg.length()-3, incomingMsg.length());

incomingMsg = incomingMsg.substring(0, incomingMsg.length()-3);
System.out.println("来自客户端的消息为:  " + incomingMsg);



String outgoingMsg = "服务端响应消息 [" + incomingMsg + "]"
+ System.getProperty("line.separator");

out.println(outgoingMsg);
out.flush();
if ("END".equals(endMSg)) {
break;
}


}
client.close();
} catch (InterruptedIOException e) {
// 超时错误
e.printStackTrace();
// IO异常
} catch (IOException e) {
// 打印错误
e.printStackTrace();
}
}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值