java网络编程
- 网络编程的目的
是指在两个或多个计算机之间实现传播交流信息,实现数据的交换与通信。 - 网络通信的要素
需要通信双方的ip,端口号,以及统一的协议
TCP:TCP 是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信。通 常用于互联网协议,被称 TCP / IP。
UDP:UDP 是用户数据报协议的缩写,一个无连接的协议。提供了应用程序之间要发送的数据的数据包。
- TCP 与 UDP对比
TCP:打电话 连接稳定
三次握手,四次挥手
最少需要三次,保证稳定连接!
A:你瞅啥?
B: 瞅你咋地?
A:干一场!
A:我要走了!
B:我真的要走了吗?
B:你真的真的要走了吗?
A:我的真的要走了!
传输完成释放连接,效率低
UDP:发短信 不连接 不稳定
TCP: Socket类------创建一个连接
创建一个类,作为客户端,创建socket对象建立连接
package org.ming.lesson1;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1.服务器的地址,端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
//2.创建socket连接
int port = 9999;
socket = new Socket(serverIP,port);
//3.发送消息,要用到IO流
os = socket.getOutputStream();
os.write("春江花月夜".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os!=null){
try {
os.close();
} catch (IOException e) {
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
创建一个作为服务端的类,建serversocket对象等待socket连接
package org.ming.lesson1;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.设置一个地址
serverSocket = new ServerSocket(9999);
while(true){
//2.等待客户端连接进来
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 (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在所有流完成任务之后,要记得关闭流并抓捕异常,好习惯。
传输文件
需用到IO流,也是分为客户端与服务端两个类,客户端发送给服务端,服务端负责接收。
客户端代码
package org.ming.lesson1;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
//客户端
public class TcpCilentDemo02 {
public static void main(String[] args) throws Exception {
//创建Socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//创建输出流
OutputStream os = socket.getOutputStream();
//读取文件
FileInputStream fis = new FileInputStream(new File("截图.jpg"));
//4.写出文件
byte[] buffer = new byte[1024];
int len;
while((len=fis.read())!=-1){
os.write(buffer,0,len);
}
//通知服务器我传输完毕了
socket.shutdownOutput();//我穿输完了
//确认服务器接收完毕才能断开
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[2014];
int len2;
while ((len2 = inputStream.read())!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//关闭资源
baos.close();
inputStream.close();
os.close();
fis.close();
socket.close();
}
}
服务端代码
package org.ming.lesson1;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class TcpServerDemo02 {
public static void main(String[] args) throws IOException {
//创建服务
ServerSocket serverSocket = new ServerSocket(9000);
//监听客户端连接
Socket socket = serverSocket.accept();
//获取输入流
InputStream is = socket.getInputStream();
//文件输出
FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read())!=-1){
fos.write(buffer,0,len);
}
//通知客户端我接受完毕了
OutputStream os = socket.getOutputStream();
os.write("接受完毕".getBytes());
//关闭资源
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
UDP
发短信,不需要互相连接,只用知道对方的地址,没有客户端与服务端,
只发送
package org.ming.lesson2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//不需要连接服务器,发送端
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//建立一个Socket
DatagramSocket socket = new DatagramSocket();
//建个包
String msg = "春江花月夜";
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();
}
}
只接受
package org.ming.lesson2;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收端
public class UdpServerDemo02 {
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().getHostAddress());
System.out.println(new String (packet.getData(),0,packet.getLength()));
//关闭
socket.close();
}
}
在一个类中使用多线程同时运行这两种方法,便可以实现发送和接受两种功能,即可实现微信一般的网络聊天功能。