前言
了解Java网络编程,打好网络编程的基础。
一、TCP消息发送
1、Client
package com.xhu.java.net;
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) {
InetAddress clientServer = null;
Socket socket = null;
OutputStream outputStream = null;
try {
clientServer = InetAddress.getByName("127.0.0.1");
int port = 9999;
socket = new Socket(clientServer, port);
outputStream = socket.getOutputStream();
outputStream.write("学TCP".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2、Server
package com.xhu.java.net;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
serverSocket = new ServerSocket(9999);
accept = serverSocket.accept();
is = accept.getInputStream();
baos = new ByteArrayOutputStream();
int n = 0;
while (true) {
try {
if (!((n = is.read()) != -1)) break;
} catch (IOException e) {
e.printStackTrace();
}
baos.write(n);
}
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 (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、UDP消息发送
UDP不建立连接,发完包就不管了。
package com.xhu.java.net;
import java.io.IOException;
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.send(new DatagramPacket("udp信息可有可无".getBytes(),
0, "udp信息可有可无".getBytes().length, InetAddress.getByName("localhost"), 9999));
socket.close();
}
}
package com.xhu.java.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
System.out.println(packet.getAddress());
socket.close();
}
}
三、UDP聊天
1、发送方
package com.xhu.java.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class UDPClientA {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9998);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = br.readLine();
byte[] msgBytes = msg.getBytes();
InetAddress receive = InetAddress.getByName("localhost");
int port = 9999;
DatagramPacket packet = new DatagramPacket(msgBytes, 0, msgBytes.length, receive, port);
socket.send(packet);
if ("bye".equalsIgnoreCase(msg)) {
br.close();
socket.close();
break;
}
}
}
}
2、接收方
package com.xhu.java.net;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPClientB {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String msg = new String(packet.getData(), 0, packet.getLength());
bw.write(packet.getAddress() + ":" + msg);
bw.flush();
bw.newLine();
if ("bye".equalsIgnoreCase(msg)) {
bw.close();
socket.close();
break;
}
}
}
}
四、多线程UDP聊天
先了解多线程入门
1、ClientA
package com.xhu.java.net;
import java.io.*;
import java.net.*;
public class UDPClientA {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9998);
Send s = new Send(socket);
Receive r = new Receive(socket);
new Thread(s).start();
new Thread(r).start();
}
static class Send implements Runnable {
private DatagramSocket socket;
public Send(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = null;
try {
msg = br.readLine();
byte[] msgBytes = msg.getBytes();
InetAddress receive = InetAddress.getByName("localhost");
int port = 9999;
DatagramPacket packet = new DatagramPacket(msgBytes, 0, msgBytes.length, receive, port);
socket.send(packet);
if ("bye".equalsIgnoreCase(msg)) {
br.close();
socket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Receive implements Runnable {
private DatagramSocket socket;
public Receive(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
try {
socket.receive(packet);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String msg = new String(packet.getData(), 0, packet.getLength());
bw.write(packet.getAddress().getHostName() + ":" + String.valueOf(packet.getPort()) + ":" + msg);
bw.flush();
bw.newLine();
bw.flush();
if ("bye".equalsIgnoreCase(msg)) {
bw.close();
socket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2、ClientB
package com.xhu.java.net;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClientB {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9999);
Send s = new Send(socket);
Receive r = new Receive(socket);
new Thread(s).start();
new Thread(r).start();
}
static class Send implements Runnable {
private DatagramSocket socket;
public Send(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String msg = null;
try {
msg = br.readLine();
byte[] msgBytes = msg.getBytes();
InetAddress receive = InetAddress.getByName("localhost");
int port = 9998;
DatagramPacket packet = new DatagramPacket(msgBytes, 0, msgBytes.length, receive, port);
socket.send(packet);
if ("bye".equalsIgnoreCase(msg)) {
br.close();
socket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Receive implements Runnable {
private DatagramSocket socket;
public Receive(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
try {
socket.receive(packet);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String msg = new String(packet.getData(), 0, packet.getLength());
bw.write(packet.getAddress().getHostName() + ":" + String.valueOf(packet.getPort()) + ":" + msg);
bw.flush();
bw.newLine();
bw.flush();
if ("bye".equalsIgnoreCase(msg)) {
bw.close();
socket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
注: 1)这里有些bug啊,比如结束时,一个线程over,应该关联另一个线程,也让它over。这里主要体现思想,能通信,仅供参考。 2)如发送、接收线程体只用写原始的两个类,可以传入socket和port来完成不同的socket的线程。
五、URL下载网络资源
package com.xhu.java.net;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownByURL {
public static void main(String[] args) {
String urlName = "https://img-baofun.zhhainiao.com/market/133/2366564fa6b83158208eb3181752a8d6_preview.mp4";
InputStream is = null;
OutputStream osw = null;
try {
URL url = new URL(urlName);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(uc.getInputStream());
osw = new BufferedOutputStream(new FileOutputStream("壁纸.mp4"));
int n = 0;
while ((n = is.read()) != -1) {
osw.write(n);
}
osw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
总结
通信靠 socket,网络通信就是socket里的InputStream / OutputStream
参考文献
[1] Java 网络编程 狂神
|