黑马程序员——Java基础——网络编程1

时间:2023-02-26 21:53:38


     ------- android培训java培训、期待与您交流! ----------


网络编程1


一、获取IP     网络编程主要在传输层 :TCP(Transmission Control Protocol)/ UDP和 网 际 层 IP(Internet Protocol)       代码示例:   
<span style="font-size:18px;">import java.net.*;

class IPDemo
{
public static void main(String[] args) throws Exception
{
//InetAddress i = InetAddress.getLocalHost();

//System.out.println(i.toString());
//System.out.println("address:"+i.getHostAddress());
//System.out.println("name:"+i.getHostName());

InetAddress ia = InetAddress.getByName("www.baidu.com");
//getHostAddress最常用,获取本机IP
System.out.println("address:"+ia.getHostAddress());
System.out.println("name:"+ia.getHostName());

}
}
</span>
运行结果:
address:119.75.218.70
name:www.baidu.com

二、UDP传输
需求:通过udp传输方式,将一段文字数据发送出去。,
定义一个udp发送端。
思路:
1,建立updsocket服务。
2,提供数据,并将数据封装到数据包中。
3,通过socket服务的发送功能,将数据包发出去。
4,关闭资源。
import java.net.*;
class UdpSend
{
public static void main(String[] args) throws Exception
{
InetAddress i= InetAddress.getLocalHost();
System.out.println(i);
//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("10.5.29.145"),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();

}
}
打开两个cmd窗口,一个作为发送端,一个座位接受段运行以上代码
运行结果: 10.5.29.145::udp ge men lai le ::8888


三、键盘录入方式数据
import java.net.*;
import java.io.*;
class UdpSend2
{
public static void main(String[] args) throws Exception
{
InetAddress i=InetAddress.getLocalHost();
System.out.println(i);
DatagramSocket ds = new DatagramSocket();

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

String line = null;

while((line=bufr.readLine())!=null)
{
if("886".equals(line))
break;

byte[] buf = line.getBytes();
 <p> //此类表示数据报包。 <span style="font-family: Arial, Helvetica, sans-serif;">数据报包用来实现无连接包投递服务</span></p>
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("10.5.29.145"),10001);ds.send(dp);}ds.close();}}class  UdpRece2{public static void main(String[] args) throws Exception{DatagramSocket ds = new DatagramSocket(10001);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());System.out.println(ip+"::"+data);}}}

        打开两个cmd窗口,一个作为发送端,一个座位接受段运行以上代码,发送端录入数据,接收端接受数据

四、UDP聊天程序设计 需求: 编写一个聊天程序。
有收数据的部分,和发数据的部分。
这两部分需要同时执行。
那就需要用到多线程技术。
一个线程控制收,一个线程控制发。

因为收和发动作是不一致的,所以要定义两个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();
//构造数据报包,用来将长度为 length 的包发送到指定主机上的指定端口号。
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("10.5.29.145"),10002);

ds.send(dp);

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,用来接收长度为 length 的数据包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();DatagramSocket receSocket = new DatagramSocket(10002);                //使该线程开始执行;Java 虚拟机调用该线程的 <code>run</code> 方法。new Thread(new Send(sendSocket)).start();new Thread(new Rece(receSocket)).start();}}


四、TCP传输
演示tcp传输。

1、tcp分客户端和服务端。
2、客户端对应的对象是Socket。服务端对应的对象是ServerSocket。

客户端,通过查阅socket对象,发现在该对象建立时,就可以去连接指定主机。
因为tcp是面向连接的。所以在建立socket服务时,
就要有服务端存在,并连接成功。形成通路后,在该通道进行数据的传输。

需求:给服务端发送给一个文本数据。定义端点接收数据并打印在控制台上。

发送端:
创建Socket服务。并指定要连接的主机和端口。

服务端:
1,建立服务端的socket服务。ServerSocket();
并监听一个端口。
2,获取连接过来的客户端对象。
通过ServerSokcet的 accept方法。没有连接就会等,所以这个方法为阻塞式的。
3,客户端如果发过来数据,那么服务端要使用对应的客户端对象,
    并获取到该客户端对象的读取流来读取发过来的数据。
并打印在控制台。
4,关闭服务端。(可选)
import java.io.*;
import java.net.*;

class TcpClient
{
public static void main(String[] args) throws Exception
{
//创建客户端的socket服务。指定目的主机和端口
Socket s = new Socket("192.168.1.254",10003);

//为了发送数据,应该获取socket流中的输出流。
OutputStream out = s.getOutputStream();

out.write("tcp ge men lai le ".getBytes());

s.close();
}
}
class  TcpServer{public static void main(String[] args) throws Exception{//建立服务端socket服务。并监听一个端口。ServerSocket ss = new ServerSocket(10003);//通过accept方法获取连接过来的客户端对象。Socket s = ss.accept();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));s.close();//关闭客户端.ss.close();}}

五、TCP应用——文件复制

属于io问题
客户端有自己的源和目的
服务端也有自己的源和目的
import java.io.*;
import java.net.*;

class TextClient
{
public static void main(String[] args) throws Exception //这里为了方便,直接抛出Exception异常
{
Socket s = new Socket("10.5.29.145",10006);

//定义客户端源
BufferedReader bufr =
new BufferedReader(new FileReader("IPDemo.java"));


//定义客户端目的
PrintWriter out = new PrintWriter(s.getOutputStream(),true);

String line = null;
while((line=bufr.readLine())!=null)
{
out.println(line);
}
//第一种结束标记,如果文件有over容易出现问题
// out.println("over")

//第二种结束标记写法
s.shutdownOutput();//关闭客户端的输出流。相当于给流中加入一个结束标记-1.

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

//读socket流
String str = bufIn.readLine();
System.out.println(str);

bufr.close();

s.close();
}
}

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

Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"....connected");


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

PrintWriter out = new PrintWriter(new FileWriter("server.txt"),true);

String line = null;

while((line=bufIn.readLine())!=null)
{
//if("over".equals(line))
//break;
out.println(line);
}

PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
pw.println("上传成功");


out.close();
s.close();
ss.close();
}
}