天天看点

android socket通信

复习下,

server端:

package com.btzh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wyb
 * @date 2019/02/16
 */
public class Server {

	public static void main(String ards[]) {
		System.out.println("--------这是服务器!");
		// 接收数据
		getData();

	}

	private static void getData() {

		try {
			// 创建serverSocket监听端口8087
			ServerSocket serverSocket = new ServerSocket(8087);
			System.out.println("-------服务监听开始了");
			// 设置允许接受数据
			Socket scSocket = serverSocket.accept();
			// 接收客户端发送的数据
			InputStream inputStream = scSocket.getInputStream();
			InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bReader = new BufferedReader(streamReader);
			String sDateString = null;
			StringBuffer sBuffer = new StringBuffer();
			while ((sDateString = bReader.readLine()) != null) {
				sBuffer.append(sDateString);
			}
			System.out.println("---服务器:" + sBuffer.toString());
			scSocket.shutdownInput();
			// 向客户端发送数据
			OutputStream oStream = scSocket.getOutputStream();
			oStream.write(("我是服务器,客户端刚刚给我发送的数据就是:" + sBuffer.toString()).getBytes());
			oStream.flush();
			scSocket.shutdownOutput();
			oStream.close();

			bReader.close();
			streamReader.close();
			inputStream.close();

			scSocket.close();
			serverSocket.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

           

client端:

package com.btzh.client;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    //输入数据
    private EditText inputedit;
    //展示服务器返回数据
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        inputedit = findViewById(R.id.inputedit);
        textView = findViewById(R.id.textview);
    }
    //点击按钮向服务器发送数据
    public void sendMes(View view) {

        sendData();
    }

    private void sendData() {
        if (TextUtils.isEmpty(inputedit.getText().toString())) {
            Toast.makeText(this, "请输入内容!", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    //本机地址+与服务器端的端口一致
                    Socket socket = new Socket("192.168.0.147", 8087);
                    OutputStream outputStream = socket.getOutputStream();
                    //发送数据
                    outputStream.write(inputedit.getText().toString().getBytes());
                    outputStream.flush();
                    socket.shutdownOutput();
                    InputStream inputStream = socket.getInputStream();
                    //接收读取服务器端的数据使用“GBK”防止乱码
                    InputStreamReader reader = new InputStreamReader(inputStream,"GBK");
                    BufferedReader bf = new BufferedReader(reader);
                    String s = null;
                    final StringBuffer stringBuffer = new StringBuffer();
                    while ((s = bf.readLine()) != null) {
                        stringBuffer.append(s);
                    }
                    
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(stringBuffer.toString());
                        }
                    });

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

    }


}
           

客户端使用时要注意连接相同局域网,开启网络权限,设置相同的端口,以及连接正确的ip地址;