黑马程序员——java基础--网络编程

------ Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------


第一章

一,网络编程        二,IP地址     三,网络模型        四、协议         五,socket

六、UDP              七、TCP传输

 

第二章

一、上传图片                二,客户端的多线程        三,自定义服务器

四,URL               五,两个类           六,逻辑地址

 

 

 

第一章

一,网络编程
   网络模型

    1.找到对方IP
    2,数据发到对方指定的       应用程序上。这些程  序用数字进行标识,  这个数字称为端口。  逻辑端口。

3,定义通信规则。这  个通信规则称为协            议。国际组织定义了        通用的协议TCP/IP.

二,IP地址
*网络中设备的标识,*本地回环地址:127.0.01。java中对应的类:InetAdress。

本地地址,测试网卡用;
   保留地址:192.168.。。
   0-65535端口范围
  0-1024系统保留端口

  80:默认网络端口

  8080:www代理端口

  3306:mysql数据库端口

  常用两种协议:UDP,TCP

三,网络模型

1、osi参考模型
 应用层:封装数据、表示层、会话层、传输层:协议、网络层:地址、数据链路层、物理层。

2、TCP/IP参考模

应用层:上3  http,ftp

传输层:TCP

网际层:IP

主机至网络层:下2

3,地址、端口

数字的逻辑标识符

:有效端口:0-65535

    系统占用或保留端口:0-1024;

四、协议

传输协议:

A、UDP

1,将数据及源封装成数2据包,面向无连接

2,数据包大小限制在64k内

3,无连接,不可靠

4,不需要建连接,速度快

::用于聊天,视频会议

B、TCP

1,建立连接,形成传输数据的通道。

2,大数据量传输

3,通过3次握手完成连接,是可靠协议

4,必须建立连接,效率稍低

::下载

五,socket

为网络服务提供的一种机制;

通信两端都有socket;

网络通信就是socket通信;

数据在两个socket间通过io传输。

六,UDP

udp发送端:
DatagramSocket

1,建立udpsocket服务。

2,提供数据,并将数据冯导数据包中。

3,通过socket服务发送数据包

4,关闭资源。

class Test1
{
	public static void main(String[] args)throws Exception
	{
		send();
	}
	
	public static void send() throws Exception
	{
		//1,建立socket服务
		DatagramSocket ds=new DatagramSocket(8888);
		byte[] buf="ni hao,wo lai le".getBytes();
		DatagramPacket dp=new DatagramPacket(buf,0,buf.length,InetAddress.getLocalHost(),10000);
		ds.send(dp);

		ds.close();
	}


	public static void sop(Object o)
	{
		System.out.println(o);
	}
}

UDP接收端:

1,定义udpsocket服务;

2,定义一个数据包,存储接收到的字节数据

3,receive数据存入数据包在

4,通过数据包的功能,取出数据;

5,关闭资源。

class Test2
{
	public static void main(String[] args)throws Exception
	{
		acept();
	}
	
	public static void acept() throws Exception
	{
		//1,建立socket服务
		DatagramSocket ds=new DatagramSocket(10000,InetAddress.getLocalHost());
		while(true)//循环监听
		{
			byte[] buf=new byte[1024];
			DatagramPacket dp=new DatagramPacket(buf,buf.length);
			ds.receive(dp); 

			String data=new String(dp.getData());
			//int port=dp.getPort();
			sop(dp.getAddress()+"   "+data+"  ");


			//ds.close();
		}	

	}


	public static void sop(Object o)
	{
		System.out.println(o);
	}
}

七、TCP传输

1,分客户端和服务端;

2,socket.severSocket

客户端:

socket以建立,就区连接主机。

因为tcp是面向连接的,所以在建立socket服务时,就要有服务端存在,并连接成功。形成通路后,在该通道进行数据传输。

步骤:

1,创建socket服务。并指定要连接的主机和端口。

2,获取socket中的流

//客户端
class Clint
{
	public static void main(String[] args) throws Exception 
	{
		Socket s=new Socket("192.168.0.100",10100);
		OutputStream out=s.getOutputStream();
		out.write("wo lai le !".getBytes());

		s.close();

	}
}

服务器端:

1,建立severSocket服务,并监听一个端口。

2,获取连接过来的客户端对象。accept

3,用。。接收数据

4,关闭服务器(KEXUAN)

class Serve
{
	public static void main(String[] args) throws Exception 
	{
		ServerSocket ss=new ServerSocket(10100);
		Socket s=ss.accept();
		String IP=s.getInetAddress().getHostName();
		System.out.println(IP);

		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();

	}
}

定义结束标记,很重要,切记切记!

 

 

第二章

 

一,上传图片
字节流;
定义结束标记;

上传图片
客户端:

1,服务端点;

2,读取客户端图片数据;

3,发给服务端;

4,读取服务端反馈信息;

5,关闭。

/*
上传图片
*/
import java.net.*;
import java.io.*;

class PClient
{
	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*5)
		{
			System.out.println("文件过大,没安好心");
			return;
		}

		Socket s=new Socket("192.168.0.100",13000);
		InputStream in=new FileInputStream(file);
		OutputStream sos=s.getOutputStream();
		InputStream sin=s.getInputStream();
		byte[] buf=new byte[1024];
		int len =0;
		while((len=in.read(buf))!=-1)
		{
				sos.write(buf,0,len);
		}
		s.shutdownOutput();
		byte[] rebuf=new byte[1024];
		String info=new String(rebuf,0,sin.read(rebuf));
		System.out.println(info);

		in.close();
		s.close();
	}
}

class PServer
{
	public static void main(String[] args)throws Exception
	{
		ServerSocket ss=new ServerSocket(13000);
		while(true)
		{
			Socket s=ss.accept();
			new Thread(new Pic(s)).start();
		}				
		
	}
}

class Pic implements Runnable
{
	private Socket s;
	public Pic(Socket s)
	{
		this.s=s;
	}

	public void run()
	{
		String ip=null;
		InputStream sin=null;
		FileOutputStream fos=null;
		OutputStream sos=null;
		try
		{
			ip=s.getInetAddress().getHostAddress();
			System.out.println(ip);

			sin=s.getInputStream();

			int count=1;
			File f=new File(ip+"_"+count+".jpg");
			while(f.exists())
			{
				f=new File(ip+"_"+(count++)+".jpg");
			}
				
			

			fos=new FileOutputStream(f);
			sos=s.getOutputStream();

			byte[] buf=new byte[1024];
			int len=0;
			while((len=sin.read(buf))!=-1)
			{
				fos.write(buf,0,len);
			}
			sos.write("上传成功".getBytes());
		}
		catch (Exception e)
		{
			System.out.println(ip+"  图片上传失败");
		}
		finally
		{
			try
			{
				fos.close();
				s.close();	
			}
			catch (Exception e)
			{
				System.out.println("资源关闭失败");
			}
			
		}
		
	}
}

二,客户端的多线程

/*
用户登陆,最多只能等3次
*/

import java.io.*;
import java.net.*;
class LoginClient 
{
	public static void main(String[] args) throws Exception
	{
		Socket s=new Socket("192.168.0.100",15000);
		

		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

		PrintWriter pw=new PrintWriter(s.getOutputStream(),true);

		BufferedReader sbr=new BufferedReader(new InputStreamReader(s.getInputStream()));

		for(int x=0;x<3;x++)
		{
			String line=br.readLine();
			if(line==null)
				break;

			pw.println(line);
			String info=sbr.readLine();
			System.out.println(info);
			if(info.contains("欢迎"))
				break;		
		}
		

		br.close();
		pw.close();
		s.close();
	}

}

class SThread implements Runnable
{
	private Socket s;
	public SThread(Socket s)
	{
		this.s=s;
	}

	public void run()
	{
		String ip=s.getInetAddress().getHostAddress();
		System.out.println(ip+"...connected");
		try
		{
			for(int x=0;x<3;x++)
			{
				BufferedReader sbr=new BufferedReader(new InputStreamReader(s.getInputStream()));
				String name=sbr.readLine();
				if(name==null)
					break;
				BufferedReader br=new BufferedReader(new FileReader("name.txt"));
				PrintWriter out=new PrintWriter(s.getOutputStream(),true);
				String line=null;

				boolean flag=false;
				while((line=br.readLine())!=null)
				{
					if(line.equals(name))
					{
						flag=true;
						break;
					}
				}
				
				if(flag)
				{
					System.out.println(name+"欢迎登陆-");
					out.println(name+"已登陆!");
				}
				else
					System.out.println(name+"正在尝试登陆...");
					out.println("用户名不存在");
				
			}
			try
			{
				s.close();
			}
			catch (Exception e)
			{
			}
			
		}
		catch (Exception e)
		{
			throw new RuntimeException(ip+"验证失败!");
		}

	}
}

class LoginServer 
{
	public static void main(String []args) throws Exception
	{
		ServerSocket ss=new ServerSocket(15000);

		while(true)
		{
			Socket s=ss.accept();

			new Thread(new SThread(s)).start();

		}
	}
}

三,自定义服务器

特殊的客服端:浏览器 

window提供的远程登陆命令:telnet

/*
	自定义服务器
*/
import java.net.*;
import java.io.*;

class MyServer
{
	public static void main(String[] args)throws Exception 
	{
		ServerSocket ss=new ServerSocket(16000);
		while(true)
		{
			Socket s=ss.accept();
			String ip=s.getInetAddress().getHostAddress();
			System.out.println(ip);
			PrintWriter out=new PrintWriter(s.getOutputStream(),true);//自动刷出数据
			out.println("<font color=red size=7>客户端你好!</font>");

			s.close();
		}		
	}
}

四,URL

URLConnection,统一资源定位,解析地址。 

String getFile() 
          获取此 URL 的文件名。 
 String getHost() 
          获取此 URL 的主机名(如果适用)。 
 String getPath() 
          获取此 URL 的路径部分。 
 int getPort() 
          获取此 URL 的端口号。 
 String getProtocol() 
          获取此 URL 的协议名称。 
MalformedURLException;

import java.io.*;
import java.net.*;
class Url
{
	public static void sop(Object o)
	{
		System.out.println(o);
	}

	public static void main(String[] args) throws Exception
	{
		String urlStr="http://detail.tmall.com/item.htm?id=39364280260";
		URL url=new URL(urlStr);
		//sop(url);
		/*
		sop(url.getProtocol());
		sop(url.getHost());
		sop(url.getPort());//-1,为默认的80端口
		sop(url.getPath());
		sop(url.getFile());
		sop("--");
		sop(url.getQuery());
		*/
		URLConnection conn=url.openConnection() ;
		//sop(conn);
		InputStream in=conn.getInputStream();

		byte[] buf=new byte[1024];

		int len=0;

		while((len=in.read(buf))!=-1)
			sop(new String(buf,0,len));	

	}
}

五,两个类
serverSocket:队列长度
SocketAddress:封装了ip+端口

想要主机名翻译成ip地址,需要域名解析。DNS
六,逻辑地址

url请求:先通过DNS找ip,返回ip,再访问;

本地主机在系统内部进行DNS解析,这样我们自己可以配置,可用来屏蔽恶意软件。


 

 

------ Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值