网络编程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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章