zoukankan      html  css  js  c++  java
  • 服务端和客户端互聊

    package socket;
     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
     
    public class Server {
     
        public static void main(String[] args) {
            try {
     
                ServerSocket ss = new ServerSocket(8888);
     
                System.out.println("监听在端口号:8888");
                Socket s = ss.accept();
     
                InputStream is = s.getInputStream();
                DataInputStream dis = new DataInputStream(is);
                OutputStream os = s.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
     
                while (true) {
                    String msg = dis.readUTF();
                    System.out.println("收到客户端信息"+msg);
                    Scanner sc = new Scanner(System.in);
                    String str = sc.next();
                    dos.writeUTF(str);
                }
     
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
        }
    }
     
     
     
     
     
     
     
    package socket;
      
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
      
    public class Client {
      
        public static void main(String[] args) {
      
            try {
                Socket s = new Socket("127.0.0.1"8888);
      
                OutputStream os = s.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                InputStream is = s.getInputStream();
                DataInputStream dis = new DataInputStream(is);
                  
                while(true){
                    Scanner sc = new Scanner(System.in);
                    String str = sc.next();
                    dos.writeUTF(str);
                    String msg = dis.readUTF();
                    System.out.println("收到服务端信息"+msg);
                }
                  
            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    linux 内存映射-ioremap和mmap函数
    vue 模板语法-插值的操作(12-22)
    chrome浏览器json插件
    vue初识(1-11)2020-10-27
    后盾人:JS课程第一章(11-18)2020-10-25
    博客园美化
    chrome 设置自动刷新网页
    二叉树的层次遍历
    poj 2905 双向队列(待补充)
    poj 2159 D
  • 原文地址:https://www.cnblogs.com/chinaifae/p/10194916.html
Copyright © 2011-2022 走看看