网络通讯

第二十三天:
网络编程:
     网络模型:
    OSI参考模型
    TCP/IP参考模型
 

       网络通讯要素:
 
       IP地址:InetAddress 
       网络中设备的标识
       不易记忆,可用主机名
       本地回环地址:127.0.0.1  主机名:localhost
 
      端口号:
      用于标识进程的逻辑地址,不同进程的标识
      有效端口:0~65535,其中0~1024系统使用或保留端口。
 
     传输协议:
     通讯的规则
     常见协议:TCP,UDP
 
     通讯过程:

UDP
将数据及源和目的封装成数据包中,不需要建立连接
每个数据报的大小在限制在64k内
因无连接,是不可靠协议
不需要建立连接,速度快

代码示例:

import java.net.*;
/*
需求:通过udp传输方式,将一段文字数据发送出去。,
定义一个udp发送端。
思路:
1,建立updsocket服务。
2,提供数据,并将数据封装到数据包中。
3,通过socket服务的发送功能,将数据包发出去。
4,关闭资源。
*/
class  UdpSend//单独的发送端
{
	public static void main(String[] args) throws Exception
	{
		//1,创建udp服务。通过DatagramSocket对象。
		DatagramSocket ds = new DatagramSocket(8888);//发送端端口
		//2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 
		byte[] buf = "udp ge men lai le ".getBytes();
		DatagramPacket dp = 
			new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000);
		//3,通过socket服务,将已有的数据包发送出去。通过send方法。
		ds.send(dp);
		//4,关闭资源。
		ds.close();
	}
}

/*
需求:
定义一个应用程序,用于接收udp协议传输的数据并处理的。
定义udp的接收端。
思路:
1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。
	方便于明确哪些数据过来该应用程序可以处理。
2,定义一个数据包,因为要存储接收到的字节数据。
因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。
3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。
4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。
5,关闭资源。
*/
class  UdpRece//单独的接收端
{
	public static void main(String[] args) throws Exception
	{
		//1,创建udp socket,建立端点。
		DatagramSocket ds = new DatagramSocket(10000);//接收端口
		while(true)
		{
		//2,定义数据包。用于存储数据。
		byte[] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf,buf.length);
		//3,通过服务的receive方法将收到数据存入数据包中。
		ds.receive(dp);//阻塞式方法。
		//4,通过数据包的方法获取其中的数据。
		String ip = dp.getAddress().getHostAddress();
		String data = new String(dp.getData(),0,dp.getLength());
		int port = dp.getPort();
		System.out.println(ip+"::"+data+"::"+port);
		}
		//5,关闭资源
		//ds.close();
	}
}


结合IO和多线程

/*
编写一个聊天程序。
有收数据的部分,和发数据的部分。
这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。
因为收和发动作是不一致的,所以要定义两个run方法。
而且这两个方法要封装到不同的类中。
*/
import java.io.*;
import java.net.*;
class Send implements Runnable//发送端线程
{
	private DatagramSocket ds;
	public Send(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			//读取键盘录入
			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));		
			String line = null;
			while((line=bufr.readLine())!=null)
			{
				byte[] buf = line.getBytes();
				//将键盘录入封装成数据包
				DatagramPacket dp = 
					new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);				
				ds.send(dp);//将键盘录入封装的数据包,发送到192.168.1.255,10002
				if("886".equals(line))
					break;
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("发送端失败");
		}
	}
}
class Rece implements Runnable//接收端线程,可接收发送端消息,以及别人发来的消息
{
	private DatagramSocket ds;
	public Rece(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			while(true)
			{
				//接收数据包
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf,buf.length);
				ds.receive(dp);//从此套接字接收数据报包
				String ip = dp.getAddress().getHostAddress();
				String data = new String(dp.getData(),0,dp.getLength());
				if("886".equals(data))
				{
					System.out.println(ip+"....离开聊天室");
					break;
				}
				System.out.println(ip+":"+data);
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("接收端失败");
		}
	}
}
class  ChatDemo//发送接收端都有,聊天工具
{
	public static void main(String[] args) throws Exception
	{
		DatagramSocket sendSocket = new DatagramSocket();//创建UDP服务
		DatagramSocket receSocket = new DatagramSocket(10002);//创建UDP服务
		new Thread(new Send(sendSocket)).start();
		new Thread(new Rece(receSocket)).start();
	}
}


TCP
建立连接,形成传输数据的通道。
在连接中进行大数据量传输
通过三次握手完成连接,是可靠协议
必须建立连接,效率会稍低
Socket客户端和ServerSocket服务器端

代码演示:

import java.io.*;
import java.net.*;
/*
演示tcp的传输的客户端和服务端的互访。
需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息。
*/

class TcpClient//客户端建立
{
	public static void main(String[] args)throws Exception 
	{	//建立客户端,指定访问的服务端IP
		Socket s = new Socket("192.168.1.254",10004);
		//获取客户端写入流
		OutputStream out = s.getOutputStream();
		//向服务端写入信息
		out.write("服务端,你好".getBytes());
		//获取客户端读取流
		InputStream in = s.getInputStream();
		//读取服务端发回的信息
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		System.out.println(new String(buf,0,len));
		//关闭客户端
		s.close();
	}
}
class TcpServer//服务端
{
	public static void main(String[] args) throws Exception
	{	//创建服务端,并定义端口
		ServerSocket ss = new ServerSocket(10004);
		//通过服务端方法,获取客户端对象。
		Socket s = ss.accept();
		//获取客户端IP地址
		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+"....connected");
		//通过客户端对象,获取客户端读取流。
		InputStream in = s.getInputStream();
		//读取客户端发来的信息
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		System.out.println(new String(buf,0,len));
		//通过客户端对象,获取客户端写入流。
		OutputStream out = s.getOutputStream();
		//想客户端写入信息。
		out.write("哥们收到,你也好".getBytes());
		s.close();//关闭客户端
		ss.close();//关闭服务端
	}
}

 

上传文件代码:

import java.io.*;
import java.net.*;
class  TextClient//客户端,上传文件 运行文件+文件路径
{
	public static void main(String[] args) throws Exception
	{
		//限定传文件的格式,大小
		if(args.length!=1)
		{
			System.out.println("请选择一个jpg格式的图片");
			return;
		}
		File file =new File(args[0]);
		if(!(file.exists()&&file.isFile()))
		{
			System.out.println("该文件有问题片");
			return;
		}
		if(!(file.getName().endsWith(".jpg"))
		{
			System.out.println("图片格式不正确");
			return;
		}
		if(!(file.length()>1024*1024*20)
		{
			System.out.println("文件过大");
			return;
		}
		//创建客户端
		Socket s = new Socket("192.168.1.254",10006);
		//关联,读取本地文件
		FileInputStream fis =new FileOutputStream(file);
		//获取客户端写入流。
		OutputStream out = s.getOutputStream();
		//将本地文件写入客户端写入流中
		byte[] buf = new byte[1024];		
		int len =0;
		while((len=fis.read(buf))!=-1)//循环标记,多理解这个地方
		{
			out.write(buf,0,len);
		}
		//告诉服务端数据已写完,shutdownOutput()禁用此套接字的(写入流)输出流。
		s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1.
		//创建客户端读取流。
		InputStream in=s.getInputStream();
		//读取服务端发回的信息
		byte[] bufIn = new byte[1024];
		int num = in.read(bufIn);
		System.out.println(new String(bufIn,0,num));

		fis.close();

		s.close();
	}
}
class PicThread implements Runnable//定义一个多线服务端
{
	private Socket s;
	PicThread(Socket s)
	{
		this.s =s;
	}
	public void run()
	{	
		int count =1;
		String ip = s.getInetAddress().getHostAddress();
		try
		{		
			System.out.println(ip+"....connected");
			//获取客户端
			InputStream in =s.getInputStream();
			//判断覆盖重名情况
			File file = new file(ip+"("+(count++)+")"+".jpg");	
			while(file.exists())//判断文件是否存在
			{
				file = new file(ip+"("+(count++)+")"+".jpg");
			}
			//关联本地文件,写入到本地。
			FileOutputStream fos  =new FileOutputStream(file);
			//将客户端读取流中读取到的信息,写入本地。
			byte[] buf = new byte[1024];		
			int len =0;
			while((len=in.read(buf))!=-1)
			{
				fos.write(buf,0,len);
			}
			//获取客户端写入流,
			OutputStream out = s.getOutputStream();
			//向客户端写入信息
			out.write("上传成功".getBytes());
			fos.close();
			s.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException(ip+"上传失败");
		}
	}
}
class  TextServer
{
	public static void main(String[] args) throws Exception
	{
		ServerSocket ss = new ServerSocket(10006);
		while(true)
		{
		//获取客户端对象
		Socket s = ss.accept();
		new Thread(new PicThread(s)).start();//多线程上传
		}
		//ss.close();
	}
}

Tomcat:就是个服务端

 

自己做IE:
传输层。
参见 URL
URLConnection去掉消息头变到应用层

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class  MyIEByGUI2
{
	private Frame f;
	private TextField tf;
	private Button but;
	private TextArea ta;	
	private Dialog d;
	private Label lab;
	private Button okBut;
	MyIEByGUI2()
	{
		init();
	}
	public void init()
	{
		f = new Frame("my window");
		f.setBounds(300,100,600,500);
		f.setLayout(new FlowLayout());
		tf = new TextField(60);
		but = new Button("转到");
		ta = new TextArea(25,70);
		d = new Dialog(f,"提示信息-self",true);
		d.setBounds(400,200,240,150);
		d.setLayout(new FlowLayout());
		lab = new Label();
		okBut = new Button("确定");
		d.add(lab);
		d.add(okBut);
		f.add(tf);
		f.add(but);
		f.add(ta);
		myEvent();
		f.setVisible(true);
	}
	private void  myEvent()
	{
		okBut.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				d.setVisible(false);
			}
		});
		d.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				d.setVisible(false);
			}
		});
		tf.addKeyListener(new KeyAdapter()
		{
			public void keyPressed(KeyEvent e)
			{
				try
				{
						if(e.getKeyCode()==KeyEvent.VK_ENTER)
					showDir();
				}
				catch (Exception ex)
				{
				}		
			}
		});
		but.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					showDir();
				}
				catch (Exception ex)
				{
				}			
			}
		});

		f.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				System.exit(0);	
			}
		});
	}
	private void showDir()throws Exception//应用层解析
	{
		ta.setText("");
		String urlPath = tf.getText();//http://192.168.1.254:8080/myweb/demo.html		
		URL url = new URL(urlPath);
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		ta.setText(new String(buf,0,len));
	}
	public static void main(String[] args) 
	{
		new MyIEByGUI2();
	}
}

//下面是传输层代码
private void showDir1()throws Exception
	{
		ta.setText("");
		String url = tf.getText();//http://192.168.1.254:8080/myweb/demo.html		
		int index1 = url.indexOf("//")+2;
		int index2 = url.indexOf("/",index1);
		String str = url.substring(index1,index2);
		String[] arr = str.split(":");
		String host = arr[0];
		int port = Integer.parseInt(arr[1]);
		String path = url.substring(index2);
		//ta.setText(str+"...."+path);
		Socket s = new Socket(host,port);	
		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
		out.println("GET "+path+" HTTP/1.1");
		out.println("Accept: */*");
		out.println("Accept-Language: zh-cn");
		out.println("Host: 192.168.1.254:11000");
		out.println("Connection: closed");
		out.println();
		out.println();
		BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String line = null;
		while((line=bufr.readLine())!=null)
		{
			ta.append(line+"\r\n");
		}
		s.close();
	}


域名解析:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值