网络编程小例子
网络编程小例子
TCP实现聊天
public class TcpClientDemo01 {
public static void main(String[] args) {
InetAddress serverIP = null;
Socket socket = null;
OutputStream os = null;
try {
//1.服务器地址、端口号
serverIP = InetAddress.getByName("localhost");
int port = 9999;
//2.创建一个socket连接
socket = new Socket(serverIP,port);
//3.发送信息 IO流
os = socket.getOutputStream();
os.write("hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != socket) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
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);
//2.等待客户端连接
socket = serverSocket.accept();
//3.读取客户端消息
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(null != baos) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != socket) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != serverSocket) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP文件上传
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(new File("exit.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
// //通知服务器我已经传输完了
// socket.shutdownOutput();
//
// //确定服务带接收完毕才能断开连接
// InputStream is = socket.getInputStream();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// byte[] buffer2=new byte[1024];
// int len2;
// while ((len2 = fis.read(buffer)) != -1){
// baos.write(buffer2,0,len2);
// }
//
// System.out.println(baos.toString());
// baos.close();
fis.close();
os.close();
socket.close();
}
}
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.png"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
// //通知客户端我接收完毕了
// OutputStream os = socket.getOutputStream();
// os.write("我接受完毕了,你可以断开了".getBytes());
//
// os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
UDP 多线程在线聊天实现
public class TalkSend implements Runnable {
//UDP 套接字
DatagramSocket socket = null;
BufferedReader reader = null;
//发送端口
private int fromPort;
//目的IP
private String toIP;
//目的端口
private int toPort;
public TalkSend(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 (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
String data = null;
try {
data = reader.readLine();
byte[] datas = data.getBytes();
//封装数据报
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length,
new InetSocketAddress(this.toIP, this.toPort));
//发送
socket.send(packet);
//从控制台读取到 bye 退出循环
if(data.equals("bye")) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
}
public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;
public TalkReceive(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[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
//接收数据报
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data, 0, packet.getLength());
System.out.println(msgFrom + ":" + receiveData);
//读取到 bye 就退出循环
if ("bye".equals(receiveData)) {
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
public class TalkStudent {
public static void main(String[] args) {
//开启两个线程,一发一收
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"teacher")).start();
}
}
public class TalkTeacher {
public static void main(String[] args) {
//开启两个线程,一发一收
new Thread(new TalkSend(6666,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"student")).start();
}
}
URL下载网络资源
public class UrlDown {
public static void main(String[] args) throws Exception {
//创建 URL
URL url = new URL("https://www.cnblogs.com/hzyuan/p/13872923.html");
//建立URL连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("aa.html");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
fos.close();
inputStream.close();
urlConnection.disconnect();
}
}
本文来自博客园,作者:hzyuan,转载请注明原文链接:https://www.cnblogs.com/hzyuan/p/15054006.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)