标签:
首先在确保服务端与客户端是相通的,ping不通肯定连不上。
TCP服务端代码
package com.example.tcp_server; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.os.Handler; import android.os.Message; import android.os.StrictMode; import android.util.Log; @SuppressLint("NewApi") public class tcpservice implements Runnable { //服务器端口 private static final int SERVERPORT = 2001; //存储所有客户端Socket连接对象 private static List<Socket> mClientList = new ArrayList<Socket>(); //线程池 private ExecutorService mExecutorService; //ServerSocket对象 private ServerSocket mServerSocket; private static PrintWriter mPrintWriter; private static String mStrMSG; public tcpservice() { try { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build()); //设置服务器端口 mServerSocket = new ServerSocket(SERVERPORT); //创建一个线程池 mExecutorService = Executors.newCachedThreadPool(); Log.e("tcpservice", "start..."); //用来临时保存客户端连接的Socket对象 new Thread(tcpservice.this).start(); } catch (IOException e) { Log.e("tcpservice", e.toString()); e.printStackTrace(); } } //接收线程发送过来信息,并用TextView显示 public static Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); Log.e("服务器说:", mStrMSG); MainActivity.AppendText("服务器说:"+mStrMSG); } }; //每个客户端单独开启一个线程 static class ThreadServer implements Runnable { private Socket mSocket; private DataInputStream dinput; public ThreadServer(Socket socket) throws IOException { this.mSocket = socket; dinput=new DataInputStream(socket.getInputStream()); SendToClient("hello,tcp server..."); } public void run() { try { byte[] bbuf = new byte[10000]; while (true) { if (!mSocket.isClosed()) { if (mSocket.isConnected()) { if (!mSocket.isInputShutdown()) { int length = dinput.read(bbuf); mStrMSG = new String(bbuf, 0, length, "gb2312"); mStrMSG += "\n"; mHandler.sendMessage(mHandler.obtainMessage()); } } } } } catch (IOException e) { e.printStackTrace(); } } } public static void SendToClient(String msg){ try{ for (Socket client : mClientList) { mPrintWriter = new PrintWriter(client.getOutputStream(), true); mPrintWriter.println(msg); } } catch(Exception e){ Log.e("向客户端发送消息败了", e.toString()); } } public void run() { try{ Socket client = null; while (true) { Log.e("tcpservice", "接收客户连接"); //接收客户连接并添加到list中 client = mServerSocket.accept(); mClientList.add(client); //开启一个客户端线程 mExecutorService.execute(new ThreadServer(client)); } } catch(Exception e){ Log.e("监听客户端", e.toString()); } } }
前端
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/myinternet_tcpclient_EditText01" android:layout_width="fill_parent" android:layout_height="200px" android:text="聊天记录:\n" > </EditText> <EditText android:id="@+id/myinternet_tcpclient_EditText02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="输入要发送的内容" > </EditText> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center" > <Button android:id="@+id/myinternet_tcpclient_BtnSend" android:layout_width="400px" android:layout_height="wrap_content" android:text="发送" /> </LinearLayout> </LinearLayout>
后台
package com.example.tcp_server; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { // 声明对象 private Button mSendButton; private static EditText mEditText01; private static EditText mEditText02; private static String TAG = "shit="; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //启动服务器 new tcpservice(); mSendButton = (Button) findViewById(R.id.myinternet_tcpclient_BtnSend); mEditText01 = (EditText) findViewById(R.id.myinternet_tcpclient_EditText01); mEditText02 = (EditText) findViewById(R.id.myinternet_tcpclient_EditText02); //发送按扭注册事件 mSendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // 取得编辑框中我们输入的内容 String str = mEditText02.getText().toString() + "\n"; mEditText01.append("我说:"+str); //向客户端发消息 tcpservice.SendToClient(str); } catch (Exception e) { Log.e(TAG, e.toString()); } } }); } public static void AppendText(String msg){ mEditText01.append(msg); } }
标签:
原文地址:http://www.cnblogs.com/huangzhen22/p/4825636.html