網絡編程UDP協議——聊天軟件

<pre class="java" name="code">class Client{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//創建客戶端,初始爲null
		Socket s=null;
		BufferedReader input=null;
		try {
			s=new Socket("192.168.1.105",10005);
			
			input=new BufferedReader(new InputStreamReader(System.in));
			
			PrintWriter out=new PrintWriter(s.getOutputStream(),true);
			InputStream in=s.getInputStream();
			String data=null;
			int len=0;
			while((data=input.readLine())!=null){
				out.println(data);
				byte[]buf=new byte[1024];
				len=in.read(buf);
				String responseData=new String(buf,0,len);
				System.out.println(responseData);
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("找不到主機");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("獲取流失敗");
		}finally{
			try {
				if(s!=null){
					s.close();	
				}
			} catch (IOException e) {
				throw new RuntimeException("套接字關閉失敗");
			}finally{
				try {
					if(input!=null)
						input.close();
				} catch (Exception e2) {
					throw new RuntimeException("鍵盤輸入流關閉失敗");
				}
			}
		}
			
		
	}
}

山寨版的聊天軟件就是這麼做成了,
說說一下UDP協議,UDP協議是一個不安全的協議,通過該協議可以將數據發送出去,而不管得不得到回覆,如上傳文件,下載文件,或者聊天軟件,文件共享等等,但是傳輸效率比較高。在應用的時候,如果不用考慮安全性,並且要求傳輸效率高的,都可以使用UDP協議進行編寫程序。

UDP協議的創建的基本步驟:

1.創建UDP協議

2.將數據打包待發送或者接收數據包

3.將打包好的數據發送或者接收數據

4.關閉相關資源

初學UDP協議的朋友,一定要記住UDP協議的創建的基本步驟,代碼記住不記住不打緊,可以通過查文檔完成,但如果不懂步驟,你再厲害,也是難完成相關項目。

發佈了66 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章