android服务端与客户端

package com.bawei.gaoying;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Y on 2017/8/22.
 * 客户端
 */

public class socket {

    private static StringBuffer stringBuffer;

    public static void main(String args[]) {
         try {
             System.out.println("客户端启动!!!");
             //创建端口号
             Socket socket = new Socket("127.0.0.1", 1227);

             PrintWriter out = new PrintWriter(socket.getOutputStream());
             out.println("服务端发来的信息是:" +"你好");
             out.flush();
             socket.shutdownOutput();

             //从控制台获取输入信息
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             String len=null;
             stringBuffer = new StringBuffer();
             while ((len=bufferedReader.readLine())!=null) {
                 stringBuffer.append(len);
             }
             System.out.println("服务端说:"+stringBuffer.toString());
             //关闭
             socket.close();
             out.close();
             bufferedReader.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
}


package com.bawei.gaoying;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Y on 2017/8/22.
 * 服务端
 */

public class servicesocket{


    private static StringBuffer stringBuffer;

    public static void main(String args[]) {

        try {
            //创建服务端
            ServerSocket serverSocket = new ServerSocket(1227);
            System.out.println("服务端启动!!!");
            //获取客户端的信息
            Socket socket = serverSocket.accept();


            //从控制台获取输入信息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String len=null;
            stringBuffer = new StringBuffer();
            while ((len=bufferedReader.readLine())!=null) {
                stringBuffer.append(len);
            }
            System.out.println("客户端说:"+stringBuffer.toString());


            PrintWriter out = new PrintWriter(socket.getOutputStream());
            out.println("客户端发来的信息是:" + "hello");
            out.flush();
            socket.shutdownOutput();

            //关闭
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}



 

你可能感兴趣的:(服务端与客户端)