Java实现Socket通信

作者: SophieSg | 来源:发表于2017-03-10 16:39 被阅读333次
    Server端代码实现
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /**
     * Created by sandy on 07/03/2017.
     */
    public class SktServer {
        public static void main (String args []) throws IOException{
    
            ServerSocket serverSocket = new ServerSocket(20034);
    
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
            String info;
            while ((info = bufferedReader.readLine()) != null){
                System.out.println("Hello, I am Server, Client say: " + info);
            }
            socket.shutdownInput();
    
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.write("Hello World!");
    
            printWriter.flush();
    
            printWriter.close();
            outputStream.close();
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
    
        }
    }
    
    Client端代码实现
    import java.io.*;
    import java.net.Socket;
    
    public class SktClient {
        public static void main (String args []) throws IOException{
            Socket socket = new Socket("127.0.0.1", 20034);
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write("name: admin; pwd: admin");
            pw.flush();
            socket.shutdownOutput();
    
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info = null;
            while ((info = br.readLine()) != null) {
                System.out.println("Hello, I am Client, Server say: " + info);
            }
    
            br.close();
            is.close();
            pw.close();
            os.close();
            socket.close();
    
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Java实现Socket通信

        本文链接:https://www.haomeiwen.com/subject/lnqogttx.html