Socket通信

public class TcpSocket {

    private static final String TAG = "TcpSocket";

    private final int eachSendSize = 2;


    public void send(final String parm) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Log.i(TAG, "send=" + parm);
                DataOutputStream dataOutStream = null;
                Socket sendSocket = null;
                try {
                    sendSocket = new Socket(Finals.IP, Finals.Port);
                    sendSocket.setTcpNoDelay(true);
                    sendSocket.setSoTimeout(500);
                    dataOutStream = new DataOutputStream(
                            sendSocket.getOutputStream());
                    byte[] jsonstring = parm.toString().getBytes();


                    ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(
                            jsonstring);

                    byte[] sendBytes = new byte[1024 * eachSendSize];
                    int length = 0;
                    while ((length = tInputStringStream.read(sendBytes, 0,
                            sendBytes.length)) > 0) {
                        dataOutStream.write(sendBytes, 0, length);
                    }
                    dataOutStream.flush();
                    sendSocket.shutdownOutput();
                    Log.i(TAG, "send完成=" + parm);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                } finally {
                    if (dataOutStream != null) {
                        try {
                            dataOutStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        if (sendSocket != null) {
                            sendSocket.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void initReceiver() {
        Log.i(TAG, "初始化接收");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int length = 0;
                    byte[] inputByte = null;
                    ServerSocket serverSocket = new ServerSocket(Finals.Port);
                    while (true) {
                        Socket socket = serverSocket.accept();
                        DataInputStream ois = new DataInputStream(
                                socket.getInputStream());


                        StringBuffer stringBuffer = new StringBuffer();
                        inputByte = new byte[1024];
                        while ((length = ois.read(inputByte, 0, inputByte.length)) > 0) {
                            stringBuffer.append(new String(inputByte).trim());
                        }

                        Log.e(TAG, "接收到=" + stringBuffer.toString());


                        ois.close();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

发送和接收使用同一个 socket


import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by cold on 16/10/13.
 */

public class TcpSocketUtils {
    private static final String TAG = "TcpSocketUtils";

    private final int eachSendSize = 2;
    private Socket sendSocket;
//    private OutputStream outputStream;
//    private InputStream inputStream;

    public TcpSocketUtils() {
        //sendSocket = new Socket();
//        initSocket();
    }

    public void initSocket() {
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.i(TAG, "开始连接");
                    sendSocket = new Socket(Finals.IP, Finals.Port);
                    sendSocket.setTcpNoDelay(true);
                    sendSocket.setSoTimeout(0);
                    Log.i(TAG, "连接connect成功=" + sendSocket.isConnected());
                    initClientReceiver();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void stopSocket() {

        if (sendSocket != null) {
            try {
                sendSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }



    public byte[] stringToBytes(String parm1) {
        parm1 = parm1.trim();
        char[] chars = parm1.toCharArray();
        int length = chars.length;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) chars[i];
//            Log.i("转换",(int)bytes[i]+"");
        }
        return bytes;
    }

    public void sendParam(final String parm) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Log.i(TAG, "send=" + parm);
                    DataOutputStream dataOutStream = new DataOutputStream(
                            sendSocket.getOutputStream());
                    //获取输入输出流
                    byte[] numer = stringToBytes(parm);
                    dataOutStream.write(numer);
                    dataOutStream.flush();
                    Log.e(TAG, "发送完成");
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                } finally {
                }
            }
        }.start();
    }

    public void initClientReceiver() {
        Log.i(TAG, "初始化客户端接收");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataInputStream ois = new DataInputStream(
                            sendSocket.getInputStream());
                    while (true){
                        StringBuffer stringBuffer = new StringBuffer();
                        byte[] inputByte = new byte[1024];
                        int length;
                        while ((length = ois.read(inputByte, 0, inputByte.length)) > 0) {
                            stringBuffer.append(new String(inputByte).trim());
                            Log.e(TAG, "客户端循环接收数据: " + stringBuffer.toString());
                        }
                        Log.e(TAG, "客户端接收数据: " + stringBuffer.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void initReceiverP() {
        Log.i(TAG, "初始化服务端接收");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int length = 0;
                    byte[] inputByte = null;
                    ServerSocket serverSocket = new ServerSocket(Finals.Port);
                    while (true) {
                        Socket socket = serverSocket.accept();
                        OutputStream out = socket.getOutputStream();
                        Log.i(TAG, "服务端accept");
                        DataInputStream ois = new DataInputStream(
                                socket.getInputStream());
                        try {
                            StringBuffer stringBuffer = new StringBuffer();
                            inputByte = new byte[1024];
                            while ((length = ois.read(inputByte, 0, inputByte.length)) > 0) {
                                stringBuffer.append(new String(inputByte).trim());
                                out.write("this is service".getBytes());
                                Log.i(TAG, "服务端接收循环=" + stringBuffer.toString());
                            }
                            Log.e(TAG, "服务端接收到=" + stringBuffer.toString());


                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            ois.close();
                            out.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

results matching ""

    No results matching ""