黑马程序员_网络编程

 ----------------- android培训java培训、期待与您交流! ----------
udp发送和接收:
发送步骤:
1,既然要进行udp协议的网络通信,当然要建立udp的socket服务.
DatagramSocket ds = new DatagramSocket(10000);

2,确定发送的具体的数据。
String str = "hi,udp 哥们来了!";
byte[] buf = str.getBytes();

3,创建数据包对象,因为udp协议是需要将数据封装到指定的数据包中。
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10000);

4,使用udpsocket服务的send方法。将数据包发出。
ds.send(dp);

5,关闭资源。
ds.close();


接收步骤:
1,创建udp socket服务对象。绑定一个指定的端口。给该应用程序分配一个数据标示。也可以称之为监听一个端口。
DatagramSocket ds = new DatagramSocket(10000);

2,创建数据包,用于存储接收到的数据,并用数据包对象的方法对数据包中的内容进行解析。
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);

3,使用socket对象的receive方法将接收到的数据都存储到数据包的对象中。
ds.receive(dp);//阻塞式方法。 

4,既然数据已经存储到数据包中,直接用数据包的方法对这些数据进行解析。 
//获取ip。
String ip = dp.getAddress().getHostAddress();
//获取port
int port = dp.getPort();
//获取数据内容。
byte[] data = dp.getData();
String text = new String(data,0,dp.getLength());
System.out.println(ip+":"+port+"::"+text);

5,关闭资源。
ds.close();


TCP客户端和服务端:
客户端:
1,创建tcp客户端对象。必须要有socket服务。客户端通常一建立,就需要去进行连接。
因为这是面向连接的协议。所以必须明确要连接那个主机,以及端口。
Socket s = new Socket("192.168.1.100",10002);

2,连接一旦建立,就形成了数据传输的通道,其实该通道就是IO流。而这个IO流是有socket建立的。
//所以称之为socket io流。该流中也有输入流和输出流。
//想要通过socket io 流获取输出流。
OutputStream out = s.getOutputStream();

3,使用输出流对象将数据写入。
 out.write("hi,tcp 哥们又来了!~".getBytes());
 
4,关闭资源。
s.close();

服务端:
1,创建tcp服务端对象。并监听一个端口。 
ServerSocket ss = new ServerSocket(10002);

2,获取客户端对象和指定的客户端进行通信。该方法是 accept();
Socket s = ss.accept();
//获取一次客户端ip地址。
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");

3,有了socket,就可以获取其中的流,必须要读取客户端的数据,需要获取读取流。
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String  text = new String(buf,0,len);
System.out.println(text);

4,关闭资源:
s.close();// 关闭客户端。
ss.close();//关闭服务端。

UDP应用实例:
package com.itheima.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPChatDemo
{

	public static void main(String[] args) throws SocketException
	{
		sop("hello,word!");
		DatagramSocket send = new DatagramSocket(10002);
		DatagramSocket rece = new DatagramSocket(10001);	
		
		new Thread(new Send(send)).start();
		new Thread(new Rece(rece)).start();
	}

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

class Send implements Runnable
{
	private DatagramSocket ds;
	
	public Send(DatagramSocket ds)
	{
		super();
		this.ds = ds;
	}

	@Override
	public void run()
	{
		try
		{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			for (;(line=br.readLine()) != null;)
			{
		
				byte[] buf = line.getBytes();
				DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10001);
				ds.send(dp);
				if ("over".equals(line))
					break;
			}
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			ds.close();
		}
	}
}

class Rece implements Runnable
{
	private DatagramSocket ds;
	
	public Rece(DatagramSocket ds)
	{
		super();
		this.ds = ds;
	}

	@Override
	public void run()
	{
		try
		{
			byte[] buf = new byte[1024];
			while (true)
			{
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				String ip = dp.getAddress().getHostAddress();
				String text = new String(dp.getData(), 0, dp.getLength());
				System.out.println(ip+":"+text);
				if ("over".equals(text))
					System.out.println(ip+"gone...");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			ds.close();
		}
	}
}


TCP应用实例:
上传图片:
客户端程序:
package com.itheima.net;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class UploadPicClient
{
	private static final String	FILE_SEPARTOR	= System.getProperty("file.separator");

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException
	{
		Socket so = new Socket("127.0.0.1" ,10027);
		
		FileInputStream fis = new FileInputStream("TempFile"+FILE_SEPARTOR+"keyboard.jpg");
		
		OutputStream out = so.getOutputStream();
		
		byte[] buf = new byte[1024];
		
		int len = 0;
		while ((len=fis.read(buf)) != -1)
		{
			out.write(buf, 0, len);
		}
		
		so.shutdownOutput();
		
		InputStream in = so.getInputStream();
		byte[] bufIn = new byte[1024];
		int lenIn = in.read(bufIn);
		String info = new String(bufIn, 0, lenIn);
		System.out.println(info);
		
		fis.close();
		so.close();
	}
}

服务端程序:
package com.itheima.net;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadPicServer
{

	private static final String	FILE_SEPAROTR	= System.getProperty("file.separator");

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException
	{
		// TODO Auto-generated method stub
		ServerSocket ss =new ServerSocket(10027);
		
		Socket s = ss.accept();
		
		System.out.println(s.getInetAddress().getHostAddress()+"----connected");
		
		InputStream in = s.getInputStream();
		
		FileOutputStream fos = new FileOutputStream("TempFile"+FILE_SEPAROTR+"up.jpg");
		
		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("upload successed!".getBytes());
		
		fos.close();
		s.close();
		ss.close();
	}

}


上传文本:
客户端程序:
package com.itheima.net;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;



public class UploadTextClient
{

	private static final String	FILE_SEPARTOR	= System.getProperty("file.separator");
	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException 
	{
		// 创建客户端socket服务
		Socket so = new Socket("127.0.0.1" ,10092);
		
		// 读取本读文件
		BufferedReader br = new BufferedReader(new FileReader("TempFile"+FILE_SEPARTOR+"uptext"));
		
		// 目的:网络
		PrintWriter out = new PrintWriter(so.getOutputStream(), true);
		String line = null;
		while ((line=br.readLine()) != null)
		{
			out.println(line);
		}
		
		// 结束标记
		so.shutdownOutput();
		
		// 给反馈信息
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(so.getInputStream()));
		String text = bufIn.readLine();
		System.out.println("server:"+text);
		bufIn.close();
		so.close();
	}
}

服务端程序:
package com.itheima.net;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadTextServer
{

	private static final String	FILE_SEPARTOR = System.getProperty("file.separator");

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException
	{
		// 创建服务端socket服务
		ServerSocket ss = new ServerSocket(10092);
		
		// 获取客户端对象
		Socket s = ss.accept();
		
		System.out.println(s.getInetAddress().getHostAddress()+"-----connected!");
		
		// 读取信息
		BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

		// 存储数据
		PrintWriter pw = new PrintWriter(new FileWriter("TempFile"+FILE_SEPARTOR+"upserver"), true);
		
		String line = null;
		while ((line=bufIn.readLine()) != null)
		{
			pw.println(line);
		}
		
		// 给反馈
		PrintWriter out = new PrintWriter(s.getOutputStream(), true);
		out.println("upload successed!");
		
		pw.close();
		s.close();
		ss.close();
	}
}

网络编程总结
1,常见的客户端和服务端。
客户端:浏览器。
服务端:Tomcat。

2,
客户端:浏览器。
服务端:自定义。 
浏览器给服务端发送的数据是:
http协议的请求消息:

GET /myweb/1.html HTTP/1.1 // 请求行 包含:  请求方式(GET,POST)空格 请求的资源路径 空格 http的协议版本。 
下面这些都是请求消息头中属性信息。
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.2; .NET4.0C)
Host: 192.168.1.100:9090
Connection: Keep-Alive
空行
请求体(这次请求没有请求体)

3,
浏览器:自定义
服务器:Tomcat。

自定义的浏览器已经收到了服务端返回的数据。

在数据之前发现以下内容:这些是HTTP协议的应答消息。

HTTP/1.1 200 OK //应答行  http协议版本  应答状态码   应答状态状态码信息码描述
应答消息头的属性信息
Server: Apache-Coyote/1.1
ETag: W/"199-1323480176984"
Last-Modified: Sat, 10 Dec 2011 01:22:56 GMT
Content-Type: text/html
Content-Length: 199
Date: Fri, 10 Aug 2012 06:55:44 GMT
Connection: close
空行
应答体
---------------------------------------
开发结构有两种:
1,C/S结构。
client / server  客户端和服务端。
特点:
  • 客户端和服务端的软件都需要程序员进行编写。
  • 客户端维护起来较为麻烦。
  • 客户端的存在可以将一部分运算分离到客户端来运行,减轻了服务器端的压力。 

2,B/S结构。
browser / server 浏览器和服务端。
特点:
  • 客户端不用程序员编写,直接使用系统中具备的浏览器软件作为客户端即可。程序员只需要编写服务器端就哦了。
  • 维护起来也很容易,因为只要维护服务器即可。
  • 所有的运算都在服务器端,相对压力较大。 










































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值