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

android 实现多线程socket通信(客户端到服务器端)

2014-07-24 13:52 369 查看
android4.0以后的版本对于在主线程中实现Socket socket = new Socket(ip,port);会报NetworkOnMainThreadException的异常,这是因为android4.0之后的版本在主线程中不能进行这种耗时的操作,所以需要新开一个线程进行socket通信的操作。

该例只是实现了从客户端每隔5秒向服务器端发送一些数据,服务器端收到后j将数据显示在控制台上,还没有实现服务器端向客户端传送数据的部分。

服务器端(java):

package com.testsocket;

import java.io.IOException;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class TestServer {

public static void main(String[] args) {

ServerSocket ss = null;

Socket socket = null;

final int PORT = 7766;

InputStream is = null;

try {

ss = new ServerSocket(PORT);

while(true){

System.out.println("**********等待客户端的socket*************");

socket = ss.accept();

System.out.println("@@@@@@@@@接收到客户端的socket@@@@@@@@@@@@");

is = socket.getInputStream();

byte buffer[] = new byte[1024];

int temp = 0;

if((temp = is.read(buffer)) != -1){

System.out.println("Server.buffer----------->" + new String(buffer,0,temp));

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

if(is != null){

try {

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(socket != null){

try {

socket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(ss != null){

try {

ss.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

客户端(android):

package com.example.testsocketdemo01;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

/**

* 功能:点击发送按钮会启动一个线程,每隔5秒向服务器发送一次socket请求并发送数据;点击取消按钮则会关闭该线程

*

* @author ZSY

*

*/

public class MainActivity extends Activity {

private Button sendBtn;

private Button finishBtn;

private Socket socket;

private final static String IP = "192.168.1.114";

private final static int PORT = 7766;

private int count = 0;

private OutputStream os = null;

private InputStream is = null;

//标识线程是否结束

private boolean flag = true;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

sendBtn = (Button) findViewById(R.id.sendBtn);

finishBtn = (Button) findViewById(R.id.finishBtn);

sendBtn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

while (flag) {

try {

socket = new Socket(IP, PORT);

//从手机的根目录下的test.txt文件读取数据

String path = Environment

.getExternalStorageDirectory()

.toString()

+ File.separator + "test.txt";

is = new FileInputStream(path);

byte buffer[] = new byte[1024];

int temp = 0;

os = socket.getOutputStream();

while ((temp = is.read(buffer)) != -1) {

os.write(buffer, 0, temp);

System.out

.println("MainActivity.buffer----------->"

+ new String(buffer, 0,

temp));

}

os.flush();

//线程睡眠5秒

Thread.sleep(5000);

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (is != null) {

try {

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (os != null) {

try {

os.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (socket != null) {

try {

socket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

}).start();

}

});

finishBtn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

//将标识置为false表示线程结束

flag = false;

}

});

}

}

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical"

>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/hello_world" />

<Button

android:id="@+id/sendBtn"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="send"

/>

<Button

android:id="@+id/finishBtn"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="finish"

/>

</LinearLayout>

注意:在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET"/>权限。

源代码下载地址:http://download.csdn.net/detail/dengfengdeling/7672473
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐