黑马程序员_网络

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------

网络编程

网络模型

OSIOpen System Interconnection开放系统互联)参考模型

TCP/IP参考模型(事实上的标准)

 

 

网络通讯要素

 IP地址:网络中设备的标识。

 

端口号:用于标识进程的逻辑地址,不同进程的标识。有效端口0~65535,其中0~1024为系统使用或保留端口。

 

传输协议:通讯的规则。

TCPUDP

TCPTransmission Control Protocol)传输控制协议

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

在连接中传输大量数据。

通过三次握手传输协议,是可靠协议。

必须建立连接,效率会稍低。

 

 

UDPUser Datagram Protocol)用户数据包协议

l 将数据及源和目的封装成数据包中,不需要建立连接。

l 每个数据报的大小限制在64k内。

l 因无连接,是不可靠协议。

l 不需要建立连接,速度快。

 

Socket

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

通信的两端都是都有Socket

网络通信其实就是网络通信其实就是Socket间的通信,数据在两个Socket间通过IO传输。

 

UDP用线程启动聊天程序代码

package net.udp.chat;

import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 启动多线程聊天。
 */
public class ChatDemo {
	public static void main(String[] args) {
		DatagramSocket send;
		try {
			send = new DatagramSocket();
			DatagramSocket receive = new DatagramSocket(8888);
			new Thread(new Send(send)).start();
			new Thread(new Receive(receive)).start();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
}


package net.udp.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 聊天程序信息接收端。
 */
public class Receive implements Runnable {
	public static final int PORT = 8888;

	private DatagramSocket ds;

	public Receive(DatagramSocket ds) {
		this.ds = ds;
	}

	@Override
	public void run() {
		while (true) {
			try {
				ds = new DatagramSocket(PORT);
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				String ip = dp.getAddress().getHostAddress();
				int port = dp.getPort();
				String data = new String(dp.getData(), 0, dp.getLength());
				System.out.printf("%s:%s说:%s%n", ip, port, data);
				if ("over".equalsIgnoreCase(data)) {
					System.out.println(ip + "...退出聊天室。");
				}
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (ds != null) {
					ds.close();
				}
			}
		}
	}
}

package net.udp.chat;

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;

/**
 * 聊天程序信息发送端。
 * @author Administrator
 * @date 2014年8月11日下午8:24:24
 */
public class Send implements Runnable {
	public static final String HOST = "127.0.0.1";

	private DatagramSocket ds;

	public Send(DatagramSocket ds) {
		this.ds = ds;
	}

	@Override
	public void run() {
		BufferedReader br = null;
		try {
			ds = new DatagramSocket();
			br = new BufferedReader(new InputStreamReader(System.in));
			String line = null;
			while ((line = br.readLine()) != null) {
				byte[] buf = line.getBytes();
				InetAddress address = InetAddress.getByName(HOST);
				DatagramPacket dp = new DatagramPacket(buf, buf.length,
						address, Receive.PORT);
				ds.send(dp);
				if ("over".equalsIgnoreCase(line)) {
					break;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ds != null) {
				ds.close();
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



TCP客户端向服务端传送一个文件

package net.tcp.upload;

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

/**
 * TCP客户端,这里向服务端发送一个文件。
 */
public class UploadClient {
	public static final String HOST = "127.0.0.1";
	public static final String UPLOAD = "D:/tmp/许巍 - 晴朗.mp3";

	public static void main(String[] args) {
		Socket s = null;
		InputStream is = null;
		try {
			s = new Socket(HOST, UploadServer.PORT);
			is = new FileInputStream(UPLOAD);

			// 向服务端发送数据
			OutputStream out = s.getOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = is.read(buf)) != -1) {
				out.write(buf, 0, len);
				out.flush();
			}
			// 传送完毕,关闭OutputStream通知服务端停止接收
			s.shutdownOutput();
			
			// 接收服务端返回的信息
			InputStream in = s.getInputStream();
			byte[] bufIn = new byte[1024];
			int lenIn = 0;
			while ((lenIn = in.read(bufIn)) != -1) {
				System.out.println(new String(bufIn, 0, lenIn));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (s != null) {
				try {
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

package net.tcp.upload;

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 UploadServer {
	public static final int PORT = 9999;
	public static final String FILEPATH = "D:/tmp/tcp_receiveFile.mp3";

	public static void main(String[] args) {
		ServerSocket ss = null;
		Socket s = null;
		OutputStream os = null;
		OutputStream out = null;
		try {
			ss = new ServerSocket(PORT);
			s = ss.accept();
			String ip = s.getInetAddress().getHostAddress();
			System.out.println("IP为" + ip + "的客户已建立连接。");
			
			InputStream in = s.getInputStream();
			out = s.getOutputStream();
			
			byte[] buf = new byte[1024];
			int len = 0;
			// 读取客户端发送过来的数据并存入本地文件
			out.write("开始接收文件".getBytes());
			os = new FileOutputStream(FILEPATH);
			while ((len = in.read(buf)) != -1) {
				os.write(buf, 0, len);
				os.flush();
			}
			out.write("接收完成".getBytes());
			s.shutdownOutput();
		} catch (IOException e) {
			try {
				out.write(("接收文件时出错。原因:" + e.getMessage()).getBytes());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			if (s != null) {
				try {
					s.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (ss != null) {
				try {
					ss.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}
}



---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! ----------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值