Socket通信编程实例(SIB和SS'SOB)

客户端:

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) {
        Socket s = null;
        InputStream is = null;
        BufferedReader br = null;
        
        try {
            s = new Socket("127.0.0.1", 6666);
            is = s.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));
            
            String str = br.readLine();
            while(str!=null){
                System.out.println(str);
                str = br.readLine();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

服务端:

package socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        OutputStream os = null;
        BufferedWriter bw = null;
        
        try {
            ss = new ServerSocket(6666);
            s = ss.accept();
            os = s.getOutputStream();
            bw = new BufferedWriter(new OutputStreamWriter(os));
            
            bw.write("hello java !");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}
原文地址:https://www.cnblogs.com/lxcmyf/p/7435441.html