socket通信的简单实现(serversocket),以及对websocket的一些认识

时间:2024-05-19 07:15:45

一、Socket 概念

socket是网络上具有唯一标识的IP地址和端口组合在一起才能构成唯一能识别的标识符套接字。

1.1:Socket原理机制:

1.通信的两端都有Socket
2.网络通信其实就是Socket间的通信
3. 数据在两个Socket间通过IO传输

1.2:Socket与Tcp/Ip:

socket通信的简单实现(serversocket),以及对websocket的一些认识
socket通信的简单实现(serversocket),以及对websocket的一些认识socket
所处位置:在应用层和下面所有层之间的位置,有了socket可以以相对简单的方式进行网络通信
本质上是帮助我们解决两个程序之间通信.----此处为博客转载

二、socket的简单实现

实现类:

Socket类
Socket(InetAddress address, int port)
创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
Socket(String host, int port)
创建一个流套接字并将其连接到指定主机上的指定端口号。
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
创建一个套接字并将其连接到指定远程地址上的指定远程端口。
Socket(String host, int port, InetAddress localAddr, int localPort)
创建一个套接字并将其连接到指定远程主机上的指定远程端口。

close()
关闭此套接字。
connect(SocketAddress endpoint)
将此套接字连接到服务器。
connect(SocketAddress endpoint, int timeout)
将此套接字连接到服务器,并指定一个超时值。
getInetAddress()
返回套接字连接的地址。
getInputStream()
返回此套接字的输入流。
getLocalPort()
返回此套接字绑定到的本地端口。
getOutputStream()
返回此套接字的输出流。
getPort()
返回此套接字连接到的远程端口。

ServerSocket类
ServerSocket(int port)
创建绑定到特定端口的服务器套接字。
accept()
侦听并接受到此套接字的连接。
getInetAddress()
返回此服务器套接字的本地地址。

Socket编程步骤
服务器端创建ServerSocket对象,调用accept方法返回Socket对象
客户端创建Socket对象,通过端口连接到服务器
客户端、服务器端都使用Socket中的getInputStream方法和getOutputStream方法获得输入流和输出流,进一步进行数据读写操作

(InetAddress用来描述主机地址;
Socket用来创建两台主机之间的连接;
ServerSocket用来侦听来自客户端的请求;
Socket通常称作“套接字”,通常通过“套接字”向网络发出请求或者应答网络请求。)
**

用socket实现简单的聊天室应用

运用多线程进行实现,创建多个client,可以对代码进行优化,采用线程池,图形化聊天窗,数据验证等,笔者这里就简单地进行实现就好了.

**

Client(客户端):

import java.io.*;
import java.net.Socket;

/**
 * @program: socket communication
 * @description: 基于serversockect的简单sockect通信
 * @author: YellowRifle
 * @create: 2019-03-22 15:19
 */
public class Client {
    public static void main(String[] args) {
        //新建sockect
        OutputStream outStream = null;
        PrintWriter pw = null;
        Socket socket = null;
        InputStream inStream = null;
        InputStreamReader inReader = null;
        BufferedReader bfReader = null;
        try {
            socket = new Socket("localhost",62345);
            //初始化输出流,发送数据到服务端
            outStream= socket.getOutputStream();
            pw= new PrintWriter(outStream);
            pw.write("userName:lucy  password:123456");
            pw.flush();
            socket.shutdownOutput();
            //初始化输入流,从服务端接收数据
            inStream = socket.getInputStream();
            inReader = new InputStreamReader(inStream);
            bfReader = new BufferedReader(inReader);

            //取出数据
            String data; //每一行的数据
            StringBuilder stringBuilder = new StringBuilder();//total data
            while((data = bfReader.readLine()) != null){
                stringBuilder.append(data);
            }
            System.out.println("I got the meassage from server:"+stringBuilder);

            //关闭输入输出流,按顺序关闭
            bfReader.close();
            inReader.close();
            inStream.close();
            pw.close();
            outStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

Server类:


import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program: socket communication
 * @description: Server
 * @author: YellowRifle
 * @create: 2019-03-22 15:55
 */
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(62345);

            int count = 0;
            //循环执行,轮循
            while (true){
               Socket socket = serverSocket.accept();
               SocketThread socketThread = new SocketThread(socket);
               socketThread.start();
               count++;
               System.out.println("客户的数量"+count);
               InetAddress address = socket.getInetAddress();System.out.println("当前客户ip"+address);

            }

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


    }
}

ServerThread(创建server,并等待多个client):

import java.io.*;
import java.net.Socket;

/**
 * @program: socket communication
 * @description: 多线程实现
 * @author: YellowRifle
 * @create: 2019-03-22 15:53
 */
public class SocketThread extends Thread {
    private Socket socket;

    public SocketThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        OutputStream outStream = null;
        PrintWriter pw = null;
        InputStream inStream = null;
        InputStreamReader inReader = null;
        BufferedReader bfReader = null;
        try {


            inStream = socket.getInputStream();
            inReader = new InputStreamReader(inStream,"utf-8");
            bfReader = new BufferedReader(inReader);
            String info;
            StringBuilder stringBuilder = new StringBuilder();
            while ((info = bfReader.readLine())!= null){
                stringBuilder.append(info);
            }
            System.out.println("i am Server the message is "+stringBuilder);
            socket.shutdownInput();
            outStream = socket.getOutputStream();
            pw = new PrintWriter(outStream );
            pw.write("welcome Client");
            pw.flush();


        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            try {
                if(pw != null) {
                    pw.close();
                }
                if(outStream != null) {

                    outStream.close();
                }
                if(bfReader != null) {
                    bfReader.close();
                }
                if(inReader != null) {
                    inReader.close();
                }
                if(inStream != null) {
                    inStream.close();
                }
                if(socket != null) {
                    socket.close();
                }
            }catch (Exception c){
                c.printStackTrace();
            }

        }


    }

}

三、websocket的一些认识

待修改---------import java.io.*;
import java.net.Socket;

/**

  • @program: socket communication

  • @description: 多线程实现

  • @author: YellowRifle

  • @create: 2019-03-22 15:53
    */
    public class SocketThread extends Thread {
    private Socket socket;

    public SocketThread(Socket socket){
    this.socket = socket;
    }
    @Override
    public void run() {
    OutputStream outStream = null;
    PrintWriter pw = null;
    InputStream inStream = null;
    InputStreamReader inReader = null;
    BufferedReader bfReader = null;
    try {

         inStream = socket.getInputStream();
         inReader = new InputStreamReader(inStream,"utf-8");
         bfReader = new BufferedReader(inReader);
         String info;
         StringBuilder stringBuilder = new StringBuilder();
         while ((info = bfReader.readLine())!= null){
             stringBuilder.append(info);
         }
         System.out.println("i am Server the message is "+stringBuilder);
         socket.shutdownInput();
         outStream = socket.getOutputStream();
         pw = new PrintWriter(outStream );
         pw.write("welcome Client");
         pw.flush();
    
    
     } catch (IOException e1) {
         e1.printStackTrace();
     }finally {
         try {
             if(pw != null) {
                 pw.close();
             }
             if(outStream != null) {
    
                 outStream.close();
             }
             if(bfReader != null) {
                 bfReader.close();
             }
             if(inReader != null) {
                 inReader.close();
             }
             if(inStream != null) {
                 inStream.close();
             }
             if(socket != null) {
                 socket.close();
             }
         }catch (Exception c){
             c.printStackTrace();
         }
    
     }
    

    }

}
import java.io.*;
import java.net.Socket;

/**

  • @program: socket communication

  • @description: 多线程实现

  • @author: YellowRifle

  • @create: 2019-03-22 15:53
    */
    public class SocketThread extends Thread {
    private Socket socket;

    public SocketThread(Socket socket){
    this.socket = socket;
    }
    @Override
    public void run() {
    OutputStream outStream = null;
    PrintWriter pw = null;
    InputStream inStream = null;
    InputStreamReader inReader = null;
    BufferedReader bfReader = null;
    try {

         inStream = socket.getInputStream();
         inReader = new InputStreamReader(inStream,"utf-8");
         bfReader = new BufferedReader(inReader);
         String info;
         StringBuilder stringBuilder = new StringBuilder();
         while ((info = bfReader.readLine())!= null){
             stringBuilder.append(info);
         }
         System.out.println("i am Server the message is "+stringBuilder);
         socket.shutdownInput();
         outStream = socket.getOutputStream();
         pw = new PrintWriter(outStream );
         pw.write("welcome Client");
         pw.flush();
    
    
     } catch (IOException e1) {
         e1.printStackTrace();
     }finally {
         try {
             if(pw != null) {
                 pw.close();
             }
             if(outStream != null) {
    
                 outStream.close();
             }
             if(bfReader != null) {
                 bfReader.close();
             }
             if(inReader != null) {
                 inReader.close();
             }
             if(inStream != null) {
                 inStream.close();
             }
             if(socket != null) {
                 socket.close();
             }
         }catch (Exception c){
             c.printStackTrace();
         }
    
     }
    

    }

}