网络编程中有两个注意问题
- 如何准确的定位到网络上的一台或多台主机
- 找到主机后如何进行通信
网络编程中的要素 - ip和端口号
- 网络通信协议
IP
ip地址类InetAddress
唯一定位一台网络上计算机
127.0.0.1:本机local
ip地址分类
IPV4:4个字节组成,0-255
IPV6:128位,无符号整数
公网ip,私网ip
//查询本机地址信息
InetAddress address1=InetAddress.getByName("127.0.0.1");
InetAddress address2=InetAddress.getByName("localhost");
InetAddress address3=InetAddress.getLocalHost();
//查询网站ip地址
InetAddress address4=InetAddress.getByName("www.baidu.com");
address4.getHostAddress();//ip
address4.getHostName();//域名
端口
端口表示计算机上的一个程序的进程
- 不同的进程有不同的端口号,用来区分软件
- 被规定为0~65535
TCP,UDP :65535*2 单个协议下,端口号不能冲突
端口分类
- 公有端口 0~1023
- http:80
- https:443
- ftp:21
- telent:23 - 程序注册端口1024~49151,分配用户或程序
Tomcat:8080
MySQL:3306
Oracle:1521 - 动态,私有端口:49152~65535
通信协议
网络通信协议:速率,传输码率,代码结构,传输控制
问题十分复杂,使用分层逐一解决
TCP/IP协议簇,实际上是一组协议
重要的协议
TCP协议:用户传输协议
UDP:用户数据报协议
IP:网络互连协议
TCP与UDP对比
TCP:打电话
- 连接,稳定
- 三次握手,四次挥手
- 客户端,服务器
- 传输完成,释放连接,效率低
UDP:发短信 - 不连接,不稳定
- 客户端服务段没有明确的界限
- 不管有没有准备好都可以发给你
如导弹攻击,DDOS(洪水攻击,饱和攻击)
TCP简易接收消息
客户端
package chatproject;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient {
public static void main(String[] args) {
Socket socket=null;
OutputStream os=null;
try {
//获取服务器相关信息
InetAddress serverIp=InetAddress.getByName("127.0.0.1");
int port=9999;
//创建socket连接
socket=new Socket(serverIp,port);
os=socket.getOutputStream();
os.write("你好,这里是客户端发送的消息".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(os!=null)
{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服务器端
package chatproject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
//服务器端口
serverSocket=new ServerSocket(9999);
//等待客户端连接
socket=serverSocket.accept();
//读取客户端消息
is=socket.getInputStream();
//管道流
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=is.read(buffer))!=-1)
{
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(baos!=null)
{
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null)
{
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP文件传输
发送文件
package file;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPFileClient {
public static void main(String[] args) throws Exception {
//设置服务器相关信息
InetAddress serverIp=InetAddress.getByName("127.0.0.1");
int port=8000;
//创建Socket连接
Socket socket=new Socket(serverIp,port);
//创建输出流
OutputStream os= socket.getOutputStream();
//读取文件
FileInputStream fis=new FileInputStream(new File("test.jpg"));
//写出文件
byte[] buffer=new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1)
{
os.write(buffer,0,len);
}
//通知服务器发送完毕
socket.shutdownOutput();
//确定服务器接收 完毕
InputStream inputStream=socket.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
buffer=new byte[1024];
while ((len=inputStream.read(buffer))!=-1)
{
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
fis.close();
os.close();
socket.close();
}
}
接收文件
package file;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPFileServer {
public static void main(String[] args) throws Exception {
//服务器端口
ServerSocket serverSocket=new ServerSocket(8000);
//等待客户端连接
Socket socket=serverSocket.accept();//阻塞式等待
//获取输入流
InputStream is=socket.getInputStream();
//文件输出
FileOutputStream fos=new FileOutputStream(new File("receive.jpg"));
byte[] bytes=new byte[1024];
int len;
while ((len=is.read(bytes))!=-1)
{
fos.write(bytes,0,len);
}
//通知客户端接收完毕
OutputStream os=socket.getOutputStream();
os.write("接收完毕".getBytes());
//关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
UDP简易发送消息
接收端
package sendmessage;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//还是要等待客户端的链接
public class UDPServer {
public static void main(String[] args) throws Exception {
//开放端口
DatagramSocket socket=new DatagramSocket(9090);
//接收数据包
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);//阻塞接收
System.out.println(packet.getAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//关闭连接
socket.close();
}
}
发送端
package sendmessage;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
//不需要连接服务器
public class UDPClient {
public static void main(String[] args) throws Exception {
//建立Socket
DatagramSocket socket=new DatagramSocket();
//建包
String msg="hello";
InetAddress localhost=InetAddress.getByName("localhost");
int port=9090;
//数据,长度起始,发送给谁
DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//发送包
socket.send(packet);
//关闭流
socket.close();
}
}
UDP简易聊天
消息发送
package udpchat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable {
private int fromPort;
private String toIP;
private int toPort;
private DatagramSocket socket;
private BufferedReader reader;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket=new DatagramSocket(fromPort);
reader=new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true)
{
try {
String data=reader.readLine();
byte[] buffer=data.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length,
new InetSocketAddress(this.toIP,this.toPort));
socket.send(packet);
if(data.equals("bye")){
System.out.println("退出");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
消息接收
package udpchat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
DatagramSocket socket;
private int port;
public TalkReceive(int port) {
this.port = port;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true)
{
try {
byte[] bytes=new byte[1024];
DatagramPacket packet=new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);//阻塞式接收数据包
byte[] data=packet.getData();
String receive=new String(data,0,data.length);
System.out.println(receive);
if(receive.equals("bye"))
{
System.out.println("退出");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
用户1
package udpchat;
public class User1 {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888)).start();
}
}
用户2
package udpchat;
public class User2 {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(6666,"localhost",8888)).start();
new Thread(new TalkReceive(9999)).start();
}
}
URL下载网络资源例子
package down;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws Exception {
//下载地址
URL url=new URL("http://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
//连接到这个资源
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
InputStream inputStream=connection.getInputStream();
FileOutputStream fos=new FileOutputStream("test.png");
byte[] bytes=new byte[1024];
int len;
while((len=inputStream.read(bytes))!=-1)
{
fos.write(bytes,0,len);
}
fos.close();
inputStream.close();
connection.disconnect();
}
}