• java Socket通信,客户端与服务端相互发消息


    1.通信过程
    网络分为应用层,http、ssh、telnet就是属于这一类,建立在传输层的基础上、其实就是定义了各自的编码解码格式,分层如下:

    2.Socket连接
    上述通信都要先在传输层有建立连接的基础上才能完成,TCP通过三次握手建立连接:
     
    Socket与http的区别可以看下这个:
    https://www.cnblogs.com/meier1205/p/5971313.html
    还有搜索:http下午茶
    3.JAVA socket 客户端与服务端互发消息
    实现结构图:
     
    客户端和服务端分别通过俩个线程来完成发送消息和接受消息,此前需要等待客户端与服务器端建立连接,这个java程序都帮你写好了,接收后就可以发消息了:
    服务端代码:
    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_Test extends Thread{
        ServerSocket server = null;
        Socket socket = null;
        public Server_Test(int port) {
            try {
                server = new ServerSocket(port);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run(){
    
            super.run();
            try{
                System.out.println("wait client connect...");
                socket = server.accept();
                new sendMessThread().start();//连接并返回socket后,再启用发送消息线程
                System.out.println(socket.getInetAddress().getHostAddress()+"SUCCESS TO CONNECT...");
                InputStream in = socket.getInputStream();
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len=in.read(buf))!=-1){
                    System.out.println("client saying: "+new String(buf,0,len));
                }
    
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    
    
        class sendMessThread extends Thread{
            @Override
            public void run(){
                super.run();
                Scanner scanner=null;
                OutputStream out = null;
                try{
                    if(socket != null){
                        scanner = new Scanner(System.in);
                        out = socket.getOutputStream();
                        String in = "";
                        do {
                            in = scanner.next();
                            out.write(("server saying: "+in).getBytes());
                            out.flush();//清空缓存区的内容
                        }while (!in.equals("q"));
                        scanner.close();
                        try{
                            out.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
    
        }
    
        //函数入口
        public static void main(String[] args) {
            Server_Test server = new Server_Test(1234);
            server.start();
        }
    }

    客户端代码

    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 extends Thread {
    
        //定义一个Socket对象
        Socket socket = null;
    
        public Client(String host, int port) {
            try {
                //需要服务器的IP地址和端口号,才能获得正确的Socket对象
                socket = new Socket(host, port);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        public void run() {
            //客户端一连接就可以写数据个服务器了
            new sendMessThread().start();
            super.run();
            try {
                // 读Sock里面的数据
                InputStream s = socket.getInputStream();
                byte[] buf = new byte[1024];
                int len = 0;
                while ((len = s.read(buf)) != -1) {
                    System.out.println(new String(buf, 0, len));
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //往Socket里面写数据,需要新开一个线程
        class sendMessThread extends Thread{
            @Override
            public void run() {
                super.run();
                //写操作
                Scanner scanner=null;
                OutputStream os= null;
                try {
                    scanner=new Scanner(System.in);
                    os= socket.getOutputStream();
                    String in="";
                    do {
                        in=scanner.next();
                        os.write((""+in).getBytes());
                        os.flush();
                    } while (!in.equals("bye"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                scanner.close();
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //函数入口
        public static void main(String[] args) {
            //需要服务器的正确的IP地址和端口号
            Client clientTest=new Client("127.0.0.1", 1234);
            clientTest.start();
        }
    }

    自己改写的,主要变化在于不用那么费事的读写

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.util.ArrayList;
    
    
    public class LuClient extends Thread {
    
        //定义一个Socket对象
        Socket socket = null;
    
        public LuClient(String host,int post){
            Exception q=null;
            while(true){
                try {
                    socket = new Socket(host,post);
           
                } catch (Exception e) {
                    q=e;
                }finally{
                    if(q==null)
                        break;
                    else
                        continue;
                    }
            }
            
        }
    
        @Override
        public void run() {
            //客户端一连接就可以写数据个服务器了
            //new sendMessThread().start();
            super.run();
            // 读Sock里面的数据
            try {
                InputStream is=socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is);
                BufferedReader br=new BufferedReader(isr);
                String message=null;
                while((message=br.readLine())!=null) {
                    if(message.equals("kaishichongxinguihua")) {
                        new sendMessThread().start();
                    }
                }
               
                
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //往Socket里面写数据,需要新开一个线程
        class sendMessThread extends Thread{
            @Override
            public void run() {
                super.run();
                //写操作
                 ArrayList<String> array=new ArrayList<String>();
                 int N = 1000;
                 int[][] Graph = {
                        { 0, 1, 1, N, N, 1, N, N, N },
                        { 1, 0, N, N, N, N, 1, N, N },
                        { 1, N, 0, 1, 1, N, N, N, N },
                        { N, N, 1, 0, N, N, N, N, N },
                        { N, N, 1, N, 0, N, N, 1, N },
                        { 1, N, N, N, N, 0, N, N, N },
                        { N, 1, N, N, N, N, 0, 1, N },
                        { N, N, N, N, 1, N, 1, 0, 1 },
                        { N, N, N, N, N, N, N, 1, 0 } };
                array=Dijkstra.dijkstra(0, Graph,8);
                
                
                try{
                    OutputStream out= socket.getOutputStream();
                    OutputStreamWriter osw = new OutputStreamWriter(out);
                    PrintWriter pw = new PrintWriter(osw, true);
                    pw.println("chongxinguihuahaole");
                    
                }catch(Exception e){
                    //e.printStackTrace();
                }
                
            }
        }
        //函数入口
        public static void main(String[] args) {
            //需要服务器的正确的IP地址和端口号
            LuClient clientTest=new LuClient("192.168.31.126",8090);
            clientTest.start();
        }
    }
  • 相关阅读:
    java全栈day01-03注释、关键字与标识符
    java全栈day01-02入门案例
    java全栈day01-01
    Python中list常用的10个基本方法----list的灰魔法
    python开发[第二篇]------str的7个必须掌握的方法以及五个常用方法
    Python开发【第二篇】:Python基本数据类型
    爬虫相关
    存储库-MongoDB简单的操作
    解析库-beautifulsoup模块
    拉勾网自动发送简历
  • 原文地址:https://www.cnblogs.com/manmanchanglu/p/12081625.html
Copyright © 2020-2023  润新知