网络编程实战
计算机网络
- TCP 建立连接–打电话
- UDP 单方面发送–发短信
计算机网络:地理位置不同的多台计算机及外部设备,通过线路在操作系统,软件,网络协议的管理协调下,达到资源共享和信息传递的目的。
- 网络编程的目的:
-
- 达到这个效果需要:
-
- 如何准确定位网络上一台主机:地址+端口号
- 定位到计算机上某个资源
- 找到主机如何传输数据
- 网络编程:TCP/IP C/S
网络通信两大要素
-
通信双方地址: -
-
规则:网络通信协议 -
-
ping 域名。
IP地址
package intStudy;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class dom1 {
public static void main(String[] args) throws UnknownHostException {
InetAddress byName = InetAddress.getByName("127.0.0.1");
InetAddress byName3 = InetAddress.getByName("localhost");
InetAddress byName4 = InetAddress.getLocalHost();
System.out.println(byName);
System.out.println(byName3);
System.out.println(byName4);
InetAddress byName2 = InetAddress.getByName("www.baidu.com");
System.out.println(byName2);
System.out.println(byName2.getAddress());
System.out.println(byName2.getCanonicalHostName());
System.out.println(byName2.getHostAddress());
System.out.println(byName2.getHostName());
}
}
端口prot
-
计算机上一个进程的编号 -
不同的进程有不同的端口 -
0~65536 -
TCP/UDP:65536*2 -
Http:80,Https:443 -
共有端口:0~1023 -
注册程序端口:1024~49151 -
- Tomcat:8080
- MySql:3306
- Ftp:23
-
动态,私有:49152~65535
import java.net.InetSocketAddress;
public class dom2 {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8089);
System.out.println(inetSocketAddress);
}
}
通信协议
- 协议-约定
- TCP:用户传输协议
- UDP:用户数据报协议
- TCP/IP协议:网络互连协议-实际上是一组协议
- TCP UDP对比
-
- TCP:打电话-连接-稳定-客户端–服务端连接-传输完成释放连接(三握四挥手)
- UDP:发短信-不连接-不稳定-客户端–服务端连接,没有明确界限-不管有没有准备都能发送
TCP实现聊天
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
public class TcpClientDom1 {
public static void main(String[] args) throws IOException {
Socket socket = null;
OutputStream os = null;
try {
InetAddress byName = InetAddress.getByName("127.0.0.1");
int port = 8899;
socket = new Socket(byName,port);
os = socket.getOutputStream();
os.write("Hallo".getBytes());
}catch (IOException e) {
e.printStackTrace();
}finally {
if(socket!=null){
socket.close();
}
if (os!=null){
os.close();
}
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDom1 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(8899);
while (true){
socket = serverSocket.accept();
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes))!=-1){
baos.write(bytes,0,len);
}
System.out.println(baos.toString());
}
} catch (Exception 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文件上传实现
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientDom3 {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getByName("localhost"), 8899);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("C:\\Users\\SS\\Desktop\\1.doc"));
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes1 = new byte[1024];
int len2;
while ((len = inputStream.read(bytes1))!=-1){
bos.write(bytes1,0,len);
}
System.out.println(bos.toString());
inputStream.close();
bos.close();
fis.close();
os.close();
socket.close();
}
}
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 TcpServerDom3 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8899);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("2");
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes))!= -1){
fos.write(bytes,0,len);
}
socket.shutdownInput();
OutputStream os = socket.getOutputStream();
os.write("over".getBytes());
}
}
UDP消息发送
-
无需连接,知道地址端口即可 -
发送端跟接收端,不存在服务器 -
Socket连接:DatagramSocket -
数据包:DatagramPacket
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
public class TcpClientDom4 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
InetAddress byName = InetAddress.getByName("localhost");
int port = 9990;
String msg = "HalloServer";
DatagramPacket pocket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,byName,port);
socket.send(pocket);
socket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TcpServerDom4 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9990);
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
UDP聊天实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
public class UdpClientDom2 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
String data = reader.readLine();
byte[] bytes = data.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress("localhost",8989));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
socket.close();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDom2 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8989);
while (true){
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
socket.receive(packet);
byte[] data = packet.getData();
String s = new String(data,0,packet.getLength());
System.out.println(s);
if(s.equals("bye")){
break;
}
}
socket.close();
}
}
UDP多线程在线聊天
两个通信方法:让原来的发送端和接收端可以互相通信
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class UdpClientDom3 implements Runnable{
DatagramSocket socket = null;
BufferedReader reader = null;
private int fromPort;
private String toIP;
private int toPort;
public UdpClientDom3(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 (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true){
try {
String data = reader.readLine();
byte[] bytes = data.getBytes();
DatagramPacket packet = new DatagramPacket(bytes,0,bytes.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();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDom3 implements Runnable{
private int port;
private String msgFrom;
DatagramSocket socket = null;
public UdpServerDom3(int port,String msgFrom){
this.port = port;
this.msgFrom = msgFrom;
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 s = new String(data,0,packet.getLength());
System.out.println(msgFrom+":"+s);
if(s.equals("bye")){
System.out.println("聊天已断开");
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class UdpClientDom4 {
public static void main(String[] args) {
new Thread(new UdpClientDom3(7777,"localhost",8888)).start();
new Thread(new UdpServerDom3(9999,"接收端")).start();
}
}
public class UdpServeDom4 {
public static void main(String[] args) {
new Thread(new UdpClientDom3(6666,"localhost",9999)).start();
new Thread(new UdpServerDom3(8888,"接收端")).start();
}
}
URL下载网络资源
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class UrlDom1 {
public static void main(String[] args) throws IOException {
URL url = new URL("http://i1.hdslb.com/bfs/face/f85fbedb0a6bfebedba167791a816e1b36f757d9.jpg");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getFile());
System.out.println(url.getQuery());
System.out.println(url.getPath());
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("file.jpg");
byte[] bytes = new byte[1024];
int len;
while ((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}
|