socket網絡編程示例代碼

/**
 * 服務器端
 * */
public class RegistServer {
    public static void main(String[] args) {
        try {
            //1.建立一個服務器Socket(ServerSocket)綁定指定端口並開始監聽
            ServerSocket serverSocket=new ServerSocket(8800);
            //2.使用accept()方法阻塞等待監聽,獲得新的連接
            Socket socket=serverSocket.accept();
            //3.獲得輸入流
            InputStream is=socket.getInputStream();
            //獲得流:可以對對象進行反序列化
            ObjectInputStream ois=new ObjectInputStream(is);
            //獲得輸出流
            OutputStream os=socket.getOutputStream();
            PrintWriter pw=new PrintWriter(os);
            //4.讀取用戶註冊信息
            User user=(User)ois.readObject();
            System.out.println("用戶註冊信息如下");
            System.out.println(user.getLoginName()+"---"+user.getLoginPwd()+"---"+user.getGender()+"---"+user.getEmail());
            //給註冊用戶一個響應
            String reply="恭喜您,註冊成功!";
            pw.write(reply);
            pw.flush();
            //5.關閉資源
            pw.close();
            os.close();
            ois.close();
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

/**
 * 客戶端
 * */
public class RegistClient {
    public static void main(String[] args) {
        try {
            //1.建立客戶端Socket連接,指定服務器的位置以及端口
            Socket socket=new Socket("localhost",8800);
            //2.得到Socket的讀寫流
            OutputStream os=socket.getOutputStream();
            //對象序列化流
            ObjectOutputStream oos=new ObjectOutputStream(os);
            //輸入流
            InputStream is=socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            //3.利用流按照一定的協議對Socket進行讀/寫操作
            User user=new User();
            user.setLoginName("Tom");
            user.setLoginPwd("123456");
            user.setGender("男");
            user.setEmail("[email protected]");
            oos.writeObject(user);
            
            socket.shutdownOutput();
            //接受服務器的響應並打印顯示
            String reply=null;
            while(!((reply=br.readLine())==null)){
                System.out.println("我是客戶端,服務器的響應爲:"+reply);
            }
            //4.關閉資源
            br.close();
            is.close();
            oos.close();
            os.close();
            socket.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章