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
该例只是实现了从客户端每隔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
相关文章推荐
- Android手机客户端通过JSP实现与Tomcat服务器端通信(Msql数据库,Json作为载体)--服务端代码
- 服务器端向Android客户端传值——登录实现(二)
- 一个简单的Android客户端从服务器端获取json数据并解析的实现代码
- android客户端从服务器端获取json数据并解析的实现代码
- Android客户端从服务器端获取json数据并解析的实现代码
- Android手机客户端通过JSP实现与Tomcat服务器端通信(Msql数据库,Json作为载体)--客户端代码
- android客户端 j2ee服务器端架构的聊天系统实现思路
- 要开发一个android项目,以android为客户端,pc为服务器端,如果实现通讯交互?
- android客户端向服务器端验证登陆方法的实现1
- Android网络编程之一个Android下菜单系统模块的实现(开桌功能))(Android客户端+服务器端Servlet+Mysql)
- 实习日志(13):服务器端向Android客户端传值——登录实现(二)
- android客户端从服务器端获取json数据并解析的实现代码
- Android仿人人客户端(v5.7.1)——对从服务器端(网络)获取的图片进行本地双缓存处理(编码实现)
- Android客户端向服务器端传值——登录实现(一)
- 服务器端和android客户端通信 服务器端实现
- Android客户端向服务器端传值——登录实现(一)
- 图片、缓存-Android仿人人客户端(v5.7.1)——对从服务器端(网络)获取的图片进行本地双缓存处理(编码实现)-by小雨
- Android仿人人客户端(v5.7.1)——对从服务器端(网络)获取的图片进行本地双缓存处理(编码实现)
- Android网络编程之——Android登录系统模块的实现(客户端+服务器端Servlet+MySQL)
- 服务器端向Android客户端传值——登录实现(二)