android用socket向服务器发送和接收消息 【转自网易闯京城的博客】

本文是一个demo,模拟一个android客户端可以持续的向socket服务器发送和从socket服务器接收消息。
先上效果图:
手机上的图:

 
 我们可以看到  手机上的消息可以发送到服务器上,服务器上的消息手机上也可以接收并显示出来。关于这个服务器端的下载地址还是要看前面的博客。 java Socket从服务器连续取消息
下面上代码:先是布局文件xml <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/et" android:inputType="textNoSuggestions" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btn" android:text="发送" android:onClick="onClick" /> <TextView android:text="消息接收区域" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FF0099" /> <EditText android:gravity="top|left|center" android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="match_parent" android:singleLine="false" android:background="#F8E0D6" /> </LinearLayout>

TestActivity.java

package com.test.com; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class TestActivity extends Activity { private EditText editText; private EditText textView; Socket socketa = null; Socket socket = null; final String IP_ADDR = "192.168.3.65";// 服务器地址 final int PORT = 8080;// 服务器端口号 private Handler handler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1) { Toast.makeText(TestActivity.this, "发送成功", 1).show(); editText.setText(""); } if (msg.what == 2) { Toast.makeText(TestActivity.this, "发送失败,请检查网络!", 1).show(); init(); } if(msg.what == 3){ String text = textView.getText().toString(); textView.setText(text + "\n" + msg.obj.toString()); } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mainlayout); editText = (EditText) findViewById(R.id.et); textView = (EditText) findViewById(R.id.tv); init(); } public void init() { ThreadPoolUtil.getInstance().execute(new Runnable() {//使用线程池 @Override public void run() { // TODO Auto-generated method stub try { socket = new Socket(IP_ADDR, PORT); receievmessage(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public void onClick(View v) { switch (v.getId()) { case R.id.btn: ThreadPoolUtil.getInstance().execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub sendmessage(); } }); break; default: break; } } // 发送消息给服务器 public void sendmessage() { try { // 向服务器端发送数据 DataOutputStream out = new DataOutputStream( socket.getOutputStream()); String str = editText.getText().toString().trim(); out.write(str.getBytes("GBK")); Message m = new Message(); m.what = 1; handler.sendMessage(m); } catch (Exception e) { e.printStackTrace(); Message m = new Message(); m.what = 2; handler.sendMessage(m); } } //接受服务器消息 public void receievmessage(){ try{ while(true){ DataInputStream input = new DataInputStream(socket.getInputStream()); byte[] buffer; buffer = new byte[input.available()]; if(buffer.length != 0){ // 读取缓冲区 input.read(buffer); String msg = new String(buffer, "GBK");//注意转码,不然中文会乱码。 Message m = new Message(); m.what = 3; m.obj = msg; handler.sendMessage(m); } } }catch (Exception e) { // TODO: handle exception e.printStackTrace(); Message m = new Message(); m.what = 2; handler.sendMessage(m); } } }

ThreadPoolUtil.java    这是自己写的一个线程池  非常好用

package com.test.com; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolUtil { private static ExecutorService instance = null; private ThreadPoolUtil() { } public static ExecutorService getInstance() { if (instance == null) instance = Executors.newCachedThreadPool(); return instance; } }

最后记得加上internet访问权限 ,就可以跑起来了。
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值