java socket学习

2018-05-26  本文已影响0人  WaterRice

Socket(套接字)

20161209121343020.jpg
socket是处在应用层之下、传输层之上的接口层,它是操作系统提供用户访问网络的接口,借助socket我们就可以对应用层、传输层和网际层的一些操作,以实现应用层的需要。下面围绕一个例子的不断优化体验java网络编程。该例子参考于https://www.cnblogs.com/yiwangzhibujian/p/7107785.html

Socket通信示例

try1:client向server发送一段信息双方即关闭
package socket;

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

public class Server {
    public static void main(String[] args) {
        final int PORT = 10086;
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        try {
            //监听10086端口
            serverSocket = new ServerSocket(PORT);
            //等待连接
            socket = serverSocket.accept();
            //获得输入流
            inputStream = socket.getInputStream();
            int len;
            //建立一个1kb的缓冲区
            byte[] bytes = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while((len = inputStream.read(bytes)) != -1){
                builder.append(new String(bytes,0,len,"UTF-8"));
            }
            System.out.println(builder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("创建失败!");
            e.printStackTrace();
        }finally{
            try {
                if(inputStream != null) inputStream.close();
                if(socket != null) socket.close();
                if(serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("关闭异常!");
                e.printStackTrace();
            }
        }
    }
}
package socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) {
        
        //要连接的ip和端口
        final String HOST = "127.0.0.1";
        final int PORT = 10086;
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //向目标发送一个连接
            socket = new Socket(HOST,PORT);
            //建立连接以后获得输出流
            outputStream = socket.getOutputStream();
            String message = "hello,server!!!";
            outputStream.write(message.getBytes("UTF-8"));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            System.out.println("请检查ip地址!");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("连接异常!");
            e.printStackTrace();
        }finally{
            try {
                if(outputStream != null) outputStream.close();
                if(socket != null) socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
try2:Server端接收到来自Client端的消息后,再发送一段消息给客户端,再关闭
package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server{
    public static void main(String[] args) {
        
        final int PORT = 10086;
        ServerSocket serverSocket = null;
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            //监听10086端口
            serverSocket = new ServerSocket(PORT);
            //等待连接
            socket = serverSocket.accept();
            //得到连接后,获得输入流
            inputStream = socket.getInputStream();
            //建立1kb的缓冲区
            byte[] bytes = new byte[1024];
            //获得client的信息
            int len;
            StringBuilder builder = new StringBuilder();
            while((len = inputStream.read(bytes)) != -1){
                builder.append(new String(bytes,0,len,"UTF-8"));
            }
            System.out.println(builder);
            //获得输出流
            outputStream = socket.getOutputStream();
            String res = "yeah I accept your message,client!";
            //向输出流响应
            outputStream.write(res.getBytes("UTF-8"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                if(inputStream != null) inputStream.close();
                if(outputStream != null) outputStream.close();
                if(socket != null) socket.close();
                if(serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client{
    public static void main(String[] args) {
        //目标的ip和端口
        final int PORT = 10086;
        final String IP = "127.0.0.1";
        
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        
        try {
            //与Server进行连接
            socket = new Socket(IP,PORT);
            //连接后获得输出流
            outputStream = socket.getOutputStream();
            String message = "hello,don't you remerber me,Server?";
            //向输出流写入message
            outputStream.write(message.getBytes("UTF-8"));
            //通过shutdownOutPut告诉Server已经发送完数据,
            socket.shutdownOutput();
            
            //获得输入流
            inputStream = socket.getInputStream();
            //建立1kb缓冲区
            byte[] bytes = new byte[1024];
            //获得server的回应
            int len;
            StringBuilder builder = new StringBuilder();
            while((len = inputStream.read(bytes)) != -1){
                builder.append(new String(bytes,0,len,"UTF-8"));
            }
            System.out.println(builder);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            System.out.println("请检查ip!");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("连接异常!");
            e.printStackTrace();
        }finally{
            try {
                if(outputStream != null) outputStream.close();
                if(inputStream != null) inputStream.close();
                if(socket != null) socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读