android实现socket端口通信demo
2016-07-08 14:39
435 查看
android实现socket端口通信demo
(1)socket通信描述Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信。两者的最大差异在于,http连接使
用的是“请求—响应方式”,即在请求时建立连接通道,当客户端向服务器发送请求后,服务器端才能向客户端
返回数据。而Socket通信则是在双方建立起连接后就可以直接进行数据的传输,在连接时可实现信息的主动推送
,而不需要每次由客户端想服务器发送请求。 那么,什么是socket?Socket又称套接字,在程序内部提供了与
外界通信的端口,即端口通信。通过建立socket连接,可为通信双方的数据传输传提供通道。socket的主要特点
有数据丢失率低,使用简单且易于移植。
TCP使用的是流的方式发送,UDP是以包的形式发送。
(2)android端
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText editText;
private TextView textView;
private Socket socket;
private String buffer = "";
public Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 1314){
Bundle bundle = msg.getData();
textView.append("server:" + bundle.getString("msg") + "\n");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
findViewById(R.id.button).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String edtext = editText.getText().toString().trim();
if (TextUtils.isEmpty(edtext)){
Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
return;
}
textView.append("client:" + edtext + "\n");
editText.setText("");
new SocketThread(edtext).start();
break;
}
}
class SocketThread extends Thread {
public String sendtext;
public SocketThread(String txt) {
this.sendtext = txt;
}
@Override
public void run() {
//定义消息
Message msg = new Message();
msg.what = 1314;
Bundle bundle = new Bundle();
bundle.clear();
try {
Log.e("chenzhongzhi","--1--");
//连接服务器,设置连接超时为5秒
socket = new Socket();
socket.connect(new InetSocketAddress("192.168.1.42", 29999), 5000);
Log.e("chenzhongzhi","--2--");
//获取流
OutputStream os = socket.getOutputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e("chenzhongzhi","--3--");
//读取服务器发来消息
String line = null;
buffer = "";
Log.e("chenzhongzhi","--4--");
while ((line = bff.readLine()) != null){
buffer = line + buffer;
}
Log.e("chenzhongzhi","--5--");
//向服务器发送消息
os.write(sendtext.getBytes("gbk"));
os.flush();
Log.e("chenzhongzhi","--6--");
bundle.putString("msg",buffer.toString());
msg.setData(bundle);
//发送消息修改textview
mHandler.sendMessage(msg);
Log.e("chenzhongzhi","--7--");
//关闭流
try {
bff.close();
}catch (Exception e){
e.printStackTrace();
}
try {
os.close();
}catch (Exception e){
e.printStackTrace();
}
try {
socket.close();
}catch (Exception e){
e.printStackTrace();
}
} catch (IOException e) {
//连接超时
bundle.putString("msg","服务器连接失败");
msg.setData(bundle);
mHandler.sendMessage(msg);
e.printStackTrace();
}
}
}
}
<LinearLayout 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:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text=".................." /> </LinearLayout>
(4)服务端
public class AndroidRunable implements Runnable{
Socket socket = null;
public AndroidRunable(Socket socket) {
super();
this.socket = socket;
}
@Override
public void run() {
String line = null;
InputStream in = null;
OutputStream out = null;
String str = "czz fydsw 1314";
try {
out = socket.getOutputStream();
in = socket.getInputStream();
BufferedReader bff = new BufferedReader(new InputStreamReader(in));
out.write(str.getBytes("gbk"));
out.flush();
socket.shutdownOutput();
while((line = bff.readLine()) != null){
System.out.println(line);
}
//关闭流
try {
out.close();
}catch (Exception e){
e.printStackTrace();
}
try {
bff.close();
}catch (Exception e){
e.printStackTrace();
}
try {
in.close();
}catch (Exception e){
e.printStackTrace();
}
try {
socket.close();
}catch (Exception e){
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class AndroidService { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(29999); while(true){ Socket socket = server.accept(); new Thread(new AndroidRunable(socket)).start(); } } }
(5)注意点
1.androidManifest添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
2.android端与服务器端的socket端口一致
相关文章推荐
- java-模拟tomcat服务器
- Linux socket 初步
- java socket 注意的地方
- java socket 注意的地方
- C#实现子窗体与父窗体通信方法实例总结
- C#基于socket模拟http请求的方法
- 简单的Ruby中的Socket编程教程
- Socket不能选择本地IP连接问题如何解决
- C#之Socket操作类实例解析
- 使用C#来编写一个异步的Socket服务器
- C#使用Socket快速判断数据库连接是否正常的方法
- java和c#使用hessian通信的方法
- 科学知识:理解socket
- websocket++简单使用及实例分析
- win32下进程间通信(共享内存)实例分析
- Android聊天工具基于socket实现
- php与flash as3 socket通信传送文件实现代码
- 解决time_wait强制关闭socket
- WinForm实现跨进程通信的方法
- C#中使用UDP通信实例