Android 之 Socket 通信
Android 之 Socket 通信
联系一下 Socket 编程,之后需要将一个 JavaEE 项目移植到 Android,暂时现尝试写一个简单的 DEMO,理解一下 Socket
Server 端编程
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 测试Android客户端与PC服务器通过socket进行交互
* 服务器端:接收客户端的信息并回送给客户
* @author Dream_Kidd
* @since 2015年06月16日11:39:14
*/
public class Server implements Runnable {
public static final int SERVERPORT = 51706;
private ServerSocket serverSocket;
public void run() {
try {
System.out.println("S: Connecting...");
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// 等待接受客户端请求
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
// 接受客户端信息
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
// 发送给客户端的消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),true);
System.out.println("S: receive a new message");
String str = in.readLine(); // 读取客户端的信息
System.out.println("S: read message over");
if (str != null ) {
// 设置返回信息,把从客户端接收的信息再返回给客户端
out.println("You sent to server message is:" + str);
out.flush();
System.out.println("S: Received: '" + str + "'");
} else {
System.out.println("Not receiver anything from client!");
}
} catch (Exception e) {
System.out.println("S: Error 1"+e.getMessage());
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error 2"+e.getMessage());
e.printStackTrace();
}
}
public static void main(String [] args ) {
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
在此处基本没什么问题,直接运行即可等待客户端连接
Client编程
1.修改manifest,在里面加上''
2.编写 Client 代码
package com.example.dream_kidd.testsocket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends Activity {
private Socket socket;
private Button bt;
private TextView tx;
private EditText et;
private static final String host = "192.168.50.73";
private static final int port = 51706;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt= (Button) findViewById(R.id.but1);
tx= (TextView) findViewById(R.id.tx1);
et= (EditText) findViewById(R.id.et);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTitle("Test Socket");
try {
socket = new Socket(host, port);
Log.d("TCP","Client...Connecting");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
//接受服务器信息
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//得到服务器信息
String msg = in.readLine();
//在页面上进行显示
tx.setText(msg);
out.println(msg);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
3.直接在 IDE 中托拉拽,生成的布局xml
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/tx1"
android:layout_width="match_parent"
android:layout_height="89dp"
android:layout_x="2dp"
android:layout_y="87dp"
android:text=" receive:" />
<Button
android:id="@+id/but1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sendmsg"
android:layout_x="277dp"
android:layout_y="11dp" />
<EditText
android:id="@+id/et"
android:layout_width="253dp"
android:layout_height="wrap_content"
android:text="请输入信息" />
</AbsoluteLayout>
然后兴冲冲的运行,结果……悲剧了
报错了,NetworkOnMainThreadException,google一下,发现这个是在安卓2.3之后,google 不允许在主线程中访问网络,
那就起一个线程,修改后代码如下
## Android 之 Socket 通信
联系一下 Socket 编程,之后需要将一个 JavaEE 项目移植到 Android,暂时现尝试写一个简单的 DEMO,理解一下 Socket
### Server 端编程
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
测试Android客户端与PC服务器通过socket进行交互
服务器端:接收客户端的信息并回送给客户
@author Dream_Kidd
@since 2015年06月16日11:39:14
*/
public class Server implements Runnable {
public static final int SERVERPORT = 51706;
private ServerSocket serverSocket;public void run() {
try {
System.out.println("S: Connecting...");serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// 等待接受客户端请求
Socket client = serverSocket.accept(); System.out.println("S: Receiving..."); try {
// 接受客户端信息
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream())); // 发送给客户端的消息
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())),true); System.out.println("S: receive a new message");
String str = in.readLine(); // 读取客户端的信息
System.out.println("S: read message over");
if (str != null ) {
// 设置返回信息,把从客户端接收的信息再返回给客户端
out.println("You sent to server message is:" + str);
out.flush();
System.out.println("S: Received: '" + str + "'");
} else {
System.out.println("Not receiver anything from client!");
}
} catch (Exception e) {
System.out.println("S: Error 1"+e.getMessage());
e.printStackTrace();
} finally {
client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error 2"+e.getMessage());
e.printStackTrace();
}
}
public static void main(String [] args ) {
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
在此处基本没什么问题,直接运行即可等待客户端连接
### Client编程
1.修改manifest,在里面加上'<uses-permission android:name="android.permission.INTERNET"/>'
2.编写 Client 代码
package com.example.dream_kidd.testsocket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends Activity {
private Socket socket;
private Button bt;
private TextView tx;
private EditText et;
private static final String host = "192.168.50.73";
private static final int port = 51706;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt= (Button) findViewById(R.id.but1);
tx= (TextView) findViewById(R.id.tx1);
et= (EditText) findViewById(R.id.et);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTitle("Test Socket");
try {
socket = new Socket(host, port);
Log.d("TCP","Client...Connecting");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
//接受服务器信息
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//得到服务器信息
String msg = in.readLine();
//在页面上进行显示
tx.setText(msg);
out.println(msg);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
3.直接在 IDE 中托拉拽,生成的布局xml
<TextView
android:id="@+id/tx1"
android:layout_width="match_parent"
android:layout_height="89dp"
android:layout_x="2dp"
android:layout_y="87dp"
android:text=" receive:" />
<Button
android:id="@+id/but1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sendmsg"
android:layout_x="277dp"
android:layout_y="11dp" />
<EditText
android:id="@+id/et"
android:layout_width="253dp"
android:layout_height="wrap_content"
android:text="请输入信息" />
```
然后兴冲冲的运行,结果……悲剧了
报错了,`NetworkOnMainThreadException`,google一下,发现这个是在安卓2.3之后,google 不允许在主线程中访问网络,
那就起一个线程,修改后代码如下
package com.example.dream_kidd.testsocket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends Activity {
private Socket socket;
private Button bt;
private TextView tx;
private EditText et;
private static final String host = "192.168.50.73";
private static final int port = 51706;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt= (Button) findViewById(R.id.but1);
tx= (TextView) findViewById(R.id.tx1);
et= (EditText) findViewById(R.id.et);
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
socket = new Socket(host, port);
Log.d("TCP","Client...Connecting");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
//接受服务器信息
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//得到服务器信息
String msg = in.readLine();
//在页面上进行显示
tx.setText(msg);
out.println(msg);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTitle("Test Socket");
t.start();
}
});
}
}
这样即可与 Service 建立连接了,但是问题很多,也仅仅只能建立连接而已,需要修改
Android 之 Socket 通信的更多相关文章
- Android之Socket通信、List加载更多、Spinner下拉列表
Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客户端向服务器发送请求后,服务 ...
- Android开发--Socket通信
一.Socket通信简介 Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是"请求-响应方式",即在请求时 ...
- 基于android的Socket通信
一.Socket通信简介 Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客户 ...
- Android中Socket通信之TCP与UDP传输原理
一.Socket通信简介 Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是"请求-响应方式",即在请求时 ...
- Android 蓝牙 socket通信
Android中蓝牙模块的使用 使用蓝牙API,Android应用程序能够执行以下功能: 扫描其他蓝牙设备查询本地已经配对的蓝牙适配器建立RFCOMM通道通过服务发现来连接其他设备在设备间传输数据管理 ...
- android adb socket 通信
今天遇到一个问题:pc客户端和android的App通信,心跳通道(心跳包27个字节,是一个业务空包)在部分pc上总是会超时(5秒超时),nagle算法也给禁用了,pc端时按按量发送心跳的,怀疑来怀疑 ...
- Android之Socket通信(一)
一.服务器端,运行在PC机上 import java.io.*; import java.net.*; public class SimpleServer{ public static voi ...
- Android中Socket通信案例
以下这个案例是基于TCP/UDP协议的. 服务端实现代码 基于TCP的服务端协议 // 声明一个ServerSocket对象 ServerSocket serverSocket = null; try ...
- Android笔记——Socket通信实现简单聊天室
两部分,客户端和服务端 ---------------------------------------------------------------- 客户端 1.为防止ANR异常,互联网连接可用 ...
随机推荐
- ashx文件的使用
转自:http://www.cnblogs.com/Tally/archive/2013/02/19/2916499.html ashx是什么文件 .ashx 文件用于写web handler的..a ...
- Constructing Roads
Constructing Roads Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- [CODEVS1014]装箱问题
题目描述 Description 有一个箱子容量为V(正整数,0<=V<=20000),同时有n个物品(0<n<=30),每个物品有一个体积(正整数). 要求n个物品中,任取若 ...
- HW4.23
public class Solution { public static void main(String[] args) { double sum = 0; for(int i = 1; i &l ...
- UILable自适应frame
UILabel *textlab = [[UILabel alloc]initWithFrame:CGRectMake(20, 10,ScrollView.frame.size.width - 40, ...
- How Do I Deploy a Windows 8 App to Another Device for Testing?
If your developing a new Windows 8 app and you want to test it on another device (e.g. Surface), you ...
- Shell编程笔记
Shell编程笔记与Windows下熟悉的批处理类似,也可以将一些重复性的命令操作写成一个脚本方便处理. 修改别人的脚本,运行后遇到个问题 setenv: command not found 查证 ...
- Struct标签
通用标签: 1. property 2. set i. 默认为action scope,会将值放入request和ActionContext中 ii. ...
- javascript中String 对象slice 和substring 区别
1.slice(start,stop)和substring(start,stop) 方法都是用于提取字符串中从start开始到stop-1间的字符(因为字符串索引是从0开始).其中 start必 ...
- 399. Evaluate Division
图像题,没觉得有什么简单的办法,貌似可以用Union Find来解. 感觉有2种思路,一种是先全部构建好每2个点的weight,然后直接遍历queires[][]来抓取答案. 一种是只构建简单的关系图 ...