java-socket通信

Socket 客户端实例

如下的 GreetingClient 是一个客户端程序,该程序通过 socket 连接到服务器并发送一个请求,然后等待一个响应。

// 文件名 GreetingClient.java
 
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      try
      {
         System.out.println("连接到主机:" + serverName + " ,端口号:" + port);
         Socket client = new Socket(serverName, port);
         System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();
         DataOutputStream out = new DataOutputStream(outToServer);
 
         out.writeUTF("Hello from " + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();
         DataInputStream in = new DataInputStream(inFromServer);
         System.out.println("服务器响应: " + in.readUTF());
         client.close();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

 

Socket 服务端实例

如下的GreetingServer 程序是一个服务器端应用程序,使用 Socket 来监听一个指定的端口。

// 文件名 GreetingServer.java
 
import java.net.*;
import java.io.*;
 
public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }
 
   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("等待远程连接,端口号为:" + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("远程主机地址:" + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt(args[0]);
      try
      {
         Thread t = new GreetingServer(port);
         t.run();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

例:

服务端监听

/**
     * 会议服务监听端口(秘书端)
     * @throws IOException
     */
    public void monitorSocketServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(1003);//指定绑定的端口,并监听此端口
        serverSocket.setSoTimeout(3000);
        Thread thread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Socket socket = serverSocket.accept();//调用accept()方法开始监听,等待客户端的连接
                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        String inin = in.readUTF();
                        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                        in.close();
                        out.close();
                        socket.close();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    } 
                }
            }
        });
        thread.start();
    }

客户端发送 

按字符串发送:

/**
     * 发送消息(会议服务处理事件)
     * @param message
     */
    @RequestMapping("/processingServices")
    @ResponseBody
    public void processingServices(String message) {
        int port = 1003;
        try {
            Socket socket = new Socket("127.0.0.1", port);
            OutputStream oStream = socket.getOutputStream();
            DataOutputStream dOutputStream = new DataOutputStream(oStream);
            dOutputStream.writeUTF(message);
            InputStream iStream = socket.getInputStream();
            DataInputStream inputStream = new DataInputStream(iStream);
            dOutputStream.close();
            inputStream.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

 按16进制发送:

    @RequestMapping("")
    @ResponseBody
    public void send() {
        DataOutputStream dataOutputStream = null;
        DataInputStream dataInputStream = null;
        Socket socket = null;
        int port = 10006;
        String instructions = "5A A5 FE AA 00 00 00 00 00 A8";
        try {
            socket = new Socket("192.168.88.142", port);
            socket.setSoTimeout(10000);
            byte[] bytes = new byte[1024];
            bytes = hexStringToBytes(instructions);
            OutputStream outputStream = socket.getOutputStream();
            dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.write(bytes);
            dataOutputStream.flush();
            InputStream inputStream = socket.getInputStream();
            dataInputStream = new DataInputStream(inputStream);
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
            try {
                dataOutputStream.close();
                dataInputStream.close();
                socket.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 16进制转换成bytes
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        //string:5AA5FEAA0000000000A8
        //bytes:[90, -91, -2, -86, 0, 0, 0, 0, 0, -88]
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.replace(" ", "");
        // toUpperCase将字符串中的所有字符转换为大写
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        // toCharArray将此字符串转换为一个新的字符数组。
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    
    /**
     * charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符
     * @param c
     * @return
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

 

posted on 2018-04-27 16:05  LJD泊水  阅读(299)  评论(0编辑  收藏  举报