java中的网络编程

1.java中的Socket API 对tcp,udp做了封装能够连接对方主机,收发数据
2.服务器端 ServerSocket
    a.可以与客户端建立连接,端口号一般使用4位以上的数字
    b.accept()方法:等待客户端连接的方法,如果没有连接,则一直等待
    代码展示:
        //服务器端口
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(5555);
        System.out.println("等待客户端连接");
        Socket accept = ss.accept();//等待连接的方法
        InputStream is = accept.getInputStream();
        byte[] bytes = new byte[1024];
        while (true) {
            int read = is.read(bytes);
            if (read == -1) {
                break;
            }
            String string = new String(bytes, 0, read);
            System.out.println(string);
        }
        accept.close();
    }
}

3.客户端 socket 
    a.客户端的对象有两个参数,第一个参数是服务器端的Ip地址,第二个参数是
    端口号(必须与服务器端的端口号一致)
    代码展示:
        //客户端口
public class Demo {
    public static void main(String[] args) throws IOException {
        Socket sk = new Socket("localhost", 5555);
        sk.getOutputStream().write("你好".getBytes());
        sk.close();
    }
}

服务器端和客户端之间通信示意图

一.改进方案一
客户端:从键盘录入数据
    代码展示:

public class Demo {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 7777);   //创建客户端
        Scanner sc = new Scanner(System.in);    //创建输入流
        while (true) {
            String s = sc.nextLine();       //从控制台输入,并且发送给服务器端
            socket.getOutputStream().write(s.getBytes());
        }
    }
}
  服务器端:把客户端传过来的数据显示到控制台上   
                    代码展示:     
   public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(7777);   //创建服务器端口号
        ExecutorService service = Executors.newCachedThreadPool();  //创建线程池
        System.out.println("等待客户端连接。。。");
        while (true) {
            Socket accept = ss.accept();        //等待客户端连接
            service.submit(() -> {          //把所要执行的代码放到线程池中执行
                try {
                    byte[] bytes = new byte[1024];        //创建字节数组
                    InputStream inputStream = accept.getInputStream();  //服务器读入客户端所传来的信息
                    while (true) {
                        int read = inputStream.read(bytes); //把读入的信息放到字节数组中
                        if (read == -1) {      //如果读到-1则结束读的过程
                            break;
                        }
                        String s = new String(bytes, 0, read);  //把读入字节数组的信息转化成字符串并且打印出来
                        System.out.println(s);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                   }

                });
            }

        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值