---------------------- android培训、java培训、期待与您交流! ----------------------
java网络编程
计算机网络是指由通信线路互相连接的许多自主工作的计算机构成的集合体,各个部件之间以何种规则进行通信,就是网络模型研究的问题。网络模型一般是指OSI七层参考模型和TCP/IP四层参考模型。这两个模型在网络中应用最为广泛。
static InetAddress |
getLocalHost() 得到本地主机
|
static InetAddress |
getByName(String host) 通过主机名称得到主机 |
String |
getHostName() 得到主机的名称 |
String |
getHostAddress() 得到主机的地址 |
static InetAddress [] |
getAllByName(String host) 根据名称得到多个主机 |
public static void getLocalHost() throws UnknownHostException {
InetAddress i = InetAddress.getLocalHost();
// 打印InetAddress
System.out.println(i);
// 打印主机名称
System.out.println("name:" + i.getHostName());
// 打印主机地址
System.out.println("address:" + i.getHostAddress());
}
输出结果:
johnny/192.168.1.102
public static void getWANHost1() throws UnknownHostException {
InetAddress i = InetAddress.getByName("www.baidu.com");
System.out.println(i);
}
控制台输出:www.baidu.com/119.75.217.56
public static void getWANHost() throws UnknownHostException {
InetAddress[] i = InetAddress.getAllByName("www.baidu.com");
for (int j = 0; j < i.length; j++) {
System.out.println(i[j]);
}
}
java.lang.Object
java.net.DatagramSocket
这个类描述了为发送和接受数据报包的Socket,常用的构造方法有
DatagramSocket(int port) DatagramSocket(int port, InetAddress laddr)
既然该类提供了发送和接受的功能,那么他就提供了这样的方法
receive(DatagramPacket p) 接受数据,把接受到的数据封装大DatagramPacket 中,这个方法是一个阻塞方法,也就是如果没有接受大数据,就会一直等待 send(DatagramPacket p) 发送数据包
java.lang.Object
java.net.DatagramPacket
该类用于别用于非连接状态下,邮寄数据服务,
atagramPacket(byte[] buf, int length, InetAddress address, int port) DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
public static void main(String[] args) throws Exception {
// 1 ,创建UDP服务,创建DatagramSocket对象
DatagramSocket socket = new DatagramSocket();
// 2,确定数据并封装成数据报包
byte[] buffer = "I'm yuzhiqiang".getBytes();
//往端口13200,主机为"192.168.1.102"发送buffer字节数组里面的数据
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
InetAddress.getByName("192.168.1.102"), 13200);
// 通过服务发送数据
socket.send(packet);
// 关闭资源
socket.close();
}
}
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(13200);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
//通过数据包获取其中的数据
String ip = packet.getAddress().getHostAddress();
String data = new String(packet.getData(),0,packet.getLength());
//获取是从哪个端口发过来的
int port = packet.getPort();
System.out.println(ip+"--"+data+"--"+port);
socket.close();
}
我们打开cmd命令,现在我们不能先运行发送数据包的程序,而是运行接收数据包的程序,因为如果接收数据包的程序没有启动发送的数据就会丢失
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket socket = new DatagramSocket();
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
byte[] buffer = line.getBytes();
// 如果把ip主机设置成192.168.1.255,那就相当于发送广播,在这个网段内活动的主机都可以收到数据
DatagramPacket packet = new DatagramPacket(line.getBytes(),
buffer.length, InetAddress.getByName("192.168.1.102"),
11111);
socket.send(packet);
}
socket.close();
}
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(11111);
while(true){
byte[] buffer = new byte[1024];
DatagramPacket p = new DatagramPacket(buffer,buffer.length);
socket.receive(p);
String ip = p.getAddress().getHostAddress();
String data = new String(p.getData(),0,p.getLength());
int port = p.getPort();
System.out.println(ip);
System.out.println("\t\t"+data+"\t"+port);
}
}
在接收端,我们能不能在把
class Send implements Runnable {
private DatagramSocket socket;
public Send(DatagramSocket socket) {
this.socket = socket;
}
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
while ((line = br.readLine()) != null) {
if ("886".equals(line))
break;
byte[] buff = line.getBytes();
//注意192.168.1.255的意义
DatagramPacket packet = new DatagramPacket(buff, buff.length,
InetAddress.getByName("192.168.1.255"), 11111);
socket.send(packet);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
socket.close();
}
}
}
class Receive implements Runnable {
private DatagramSocket socket;
public Receive(DatagramSocket socket) {
this.socket = socket;
}
public void run() {
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
String ip = packet.getAddress().getHostAddress();
String data = new String(packet.getData(), 0, packet
.getLength());
System.out.println(ip);
System.out.println("\t" + data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试程序:
public class ChatTest {
public static void main(String[] args) throws SocketException {
DatagramSocket receive = new DatagramSocket(11111);
DatagramSocket send = new DatagramSocket();
new Thread(new Send(send)).start();
new Thread(new Receive(receive)).start();
}
}
结果如图:
//服务器端
public class TcpDemo {
public static void main(String[] args) throws IOException {
//建立一个服务端的Socket服务,并监听(绑定)10001端口
ServerSocket server = new ServerSocket(10001);
//获取连接到的客户端对象,此方法是阻塞式方法,因为没有客户端连接 ,就一直等待
Socket client = server.accept();
String ip = client.getInetAddress().getHostAddress();
//打印连接服务器的客户端IP
System.out.println(ip+"connected...");
InputStream is = client.getInputStream();
byte[] buff = new byte[1024];
int len = is.read(buff);
System.out.println(new String(buff,0,len));
client.close();
//只服务一次
server.close();
}
}
//客户端
class Client {
public static void main(String[] args) throws Exception {
// 创建客户端的Socket服务,并指定主机和端口
Socket client = new Socket("192.168.1.102", 10001);
// 得到输出流,往服务端发送数据
OutputStream os = client.getOutputStream();
os.write("你好".getBytes());
client.close();
}
}
//服务器端
public class TcpDemo2 {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(22223);
Socket client = server.accept();
String ip = client.getInetAddress().getHostAddress();
System.out.println(ip+".....connected!");
InputStream is = client.getInputStream();
byte[] buff = new byte[1024];
int len = is.read(buff);
String message = new String(buff, 0, len);
System.out.println(message);
OutputStream os = client.getOutputStream();
os.write(("我已经收到你信息:"+"\""+message+"\"").getBytes());
client.close();
server.close();
}
}
//客户端
class Client2 {
public static void main(String[] args) throws Exception {
Socket client = new Socket("192.168.1.102", 22223);
OutputStream os = client.getOutputStream();
// 向服务器发数据
os.write("你好啊!".getBytes());
InputStream is = client.getInputStream();
byte[] buff = new byte[1024];
// 读取服务器发来的数据/read方法是阻塞式方法,没有读到数据就会等
int len = is.read(buff);
System.out.println(new String(buff, 0, len));
client.close();
}
}
public class TcpTask {
public static void main(String[] args) throws IOException {
// 监听或绑定23456端口
ServerSocket server = new ServerSocket(23456);
// 获取客户端对象
Socket client = server.accept();
BufferedReader buffIn = new BufferedReader(new InputStreamReader(client
.getInputStream()));
BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(
client.getOutputStream()));
String line = null;
while ((line = buffIn.readLine()) != null) {
buffOut.write(line);
System.out.println(line);
}
client.close();
server.close();
}
}
class Client3 {
public static void main(String[] args) throws Exception {
// 获取服务器对象
Socket client = new Socket("192.168.1.102", 23456);
// 首先要获取键盘录入, 转换流就不再介绍了
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(
client.getOutputStream()));
BufferedReader buffIn = new BufferedReader(new InputStreamReader(client
.getInputStream()));
while ((line = br.readLine()) != null) {
if ("over".equals(line))
break;
buffOut.write(line);
String serverLine = buffIn.readLine();
System.out.println(serverLine.toUpperCase());
}
br.close();
client.close();
}
}按照步骤运行上面的程序
服务器端正在阻塞
客户端正在等我输入:
输入数据后,
发现服务端任然没有什么变化,并且客户端也无法再次输入数据.为什么会出现这么奇怪的现象呢?
首先我们来看两段代码
客户端代码片段
while ((line = br.readLine()) != null) {
if ("over".equals(line))
break;
buffOut.write(line);
String serverLine = buffIn.readLine();
System.out.println(serverLine.toUpperCase());
}
服务端代码片段:
while ((line = buffIn.readLine()) != null) {
buffOut.write(line);
System.out.println(line);
}
while ((line = br.readLine()) != null) {
if ("over".equals(line))
break;
buffOut.write(line);
buffOut.newLine();
buffOut.flush();
String serverLine = buffIn.readLine();
System.out.println(serverLine.toUpperCase());
}
while ((line = buffIn.readLine()) != null) {
buffOut.write(line);
buffOut.newLine();
buffOut.flush();
System.out.println(line);
}
重新编译,再运行结果如图:
服务端
客户端:
public static void main(String[] args) throws Exception {
InputStream is = System.in;
OutputStream os = new FileOutputStream("test3.txt");
byte[] buff = new byte[10];
int len = is.read(buff);
System.out.println(len);
os.write(buff, 0, len);
os.close();
}
public static void main(String[] args) throws Exception {
// 字符缓冲流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
OutputStream os = new FileOutputStream("test3.txt");
String line = br.readLine();
System.out.println(line.length());
os.write(line.getBytes());
}
public class TcpCopyFile {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(65432);
Socket socket = ss.accept();
String ip = socket.getInetAddress().getHostAddress();
System.out.println(ip+".....connected!");
// 用该对象读取客户端发来的信息
BufferedReader br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
// 把读到的内容保存到指定 的文件中
PrintWriter pw = new PrintWriter(new FileWriter("testCopy.txt"), true);
String line = null;
while ((line = br.readLine()) != null) {
pw.println(line);
}
// 把信息反馈给客户端
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("上传完毕");
out.close();
pw.close();
socket.close();
ss.close();
}
}
class Client4 {
public static void main(String[] args) throws Exception {
// 创建客户端服务
Socket socket = new Socket("192.168.1.102", 65432);
// 读取test.txt文件
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
// 把文件的内容发送到客户端
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String line = null;
while ((line = br.readLine()) != null) {
pw.println(line);
}
// 读取服务器发送的反馈信息
BufferedReader buffIn = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String message = buffIn.readLine();
System.out.println(message);
//关闭资源
buffIn.close();
pw.close();
br.close();
socket.close();
}
}
while ((line = br.readLine()) != null) {
pw.println(line);
}
// 读取服务器发送的反馈信息
BufferedReader buffIn = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
String message = buffIn.readLine();
while ((line = br.readLine()) != null) {
pw.println(line);
}
// 把信息反馈给客户端
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("上传完毕");
while ((line = br.readLine()) != null) {
pw.println(line);
}
//当发完数据后,告诉服务器端,我不在传输数据了
socket.shutdownOutput();
---------------------- android培训、java培训、期待与您交流! ----------------------