Skip to content

Instantly share code, notes, and snippets.

@yzh5675
Created June 9, 2021 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzh5675/bfd8699364a322e5e3e7582f439ac748 to your computer and use it in GitHub Desktop.
Save yzh5675/bfd8699364a322e5e3e7582f439ac748 to your computer and use it in GitHub Desktop.
多线程及网络编程的实现
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CheckStyle-IDEA">
<option name="configuration">
<map>
<entry key="checkstyle-version" value="8.41.1" />
<entry key="copy-libs" value="true" />
<entry key="location-0" value="BUNDLED:(bundled):Sun Checks" />
<entry key="location-1" value="BUNDLED:(bundled):Google Checks" />
<entry key="scan-before-checkin" value="false" />
<entry key="scanscope" value="JavaOnly" />
<entry key="suppress-errors" value="false" />
</map>
</option>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PublishConfigData" persistUploadOnCheckin="false" />
</project>
<html>Simple <b>Java</b> application that includes a class with <code>main()</code> method</html>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" defaultCharsetForPropertiesFiles="UTF-8">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="Date,date" />
</inspection_tool>
</profile>
</component>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectKey">
<option name="state" value="project://e2804f05-5315-4fc6-a121-c522a6c26470" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_9" default="true" project-jdk-name="9" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/JavaBase.iml" filepath="$PROJECT_DIR$/JavaBase.iml" />
</modules>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MyBatisCodeHelperDatasource">
<option name="projectProfile">
<ProjectProfile>
<option name="baseClassSearchXml" value="true" />
</ProjectProfile>
</option>
</component>
</project>
<template>
<input-field default="com.company">IJ_BASE_PACKAGE</input-field>
</template>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="CheckStyle-IDEA-Module">
<option name="configuration">
<map />
</option>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
package com.cs.exec;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 15:36
**/
public class PicClient {
public static void main(String[] args) {
//args是用来传参
if(args.length != 1) {
System.out.println("请选择一个png图片");
return;
}
File file = new File(args[0]);
if(!(file.exists() && file.isFile())) {
System.out.println("图片不存在");
return;
}
if(!file.getName().endsWith(".png")) {
System.out.println("该文件不是一张图片");
return;
}
if(file.length() > 1024*1024*5){
System.out.println("文件过大");
return;
}
Socket s = null;
OutputStream os = null;
InputStream is = null;
FileInputStream fis = null;
try {
s = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
os =s.getOutputStream();
//读取文件
fis = new FileInputStream(file);
byte[] b = new byte[128];
int len;
while((len = fis.read(b)) != -1) {
os.write(b, 0, len);
}
//告诉服务端我已经传输完成
s.shutdownOutput();
//得到返回输入流
is = s.getInputStream();
//4:从输入流解析 成数据
byte[] bb = new byte[128];
int len1;
while((len1 = is.read(bb)) != -1) {
String str = new String(bb, 0, len1);
System.out.println(str);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(is != null) {
is.close();
}
if(os != null) {
os.close();
}
if(s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cs.exec;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 16:47
**/
public class PicServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9090);
System.out.println("Pic Server is Running....");
while (true) {
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
}
}
package com.cs.exec;
import java.io.*;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 15:01
**/
public class PicThread implements Runnable {
private Socket s;
private static int index = 0;
public PicThread(Socket s) {
this.s = s;
}
@Override
public void run() {
InputStream is = null;
FileOutputStream fos = null;
OutputStream os = null;
//得到 客户端的IP
String ip = s.getInetAddress().getHostAddress();
//int index = 0;
try {
File f = new File("d:\\test\\");
if (!f.exists()) {
f.mkdir();
}
//127.0.0.1(1).png
File file = new File("d:\\test\\" + ip + "(" + index + ").png");
if (file.exists()) {
file = new File("d:\\test\\" + ip + "(" + ++index + ").png");
}
fos = new FileOutputStream(file);
//得到图片上传的输入流数据
is = s.getInputStream();
byte[] b = new byte[256];
int len;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
System.out.println("收到来自于" + s.getInetAddress().getHostAddress() + "的文件");
os = s.getOutputStream();
os.write("发送成功".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (fos != null) {
fos.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cs.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/08/ 9:26
**/
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress add = InetAddress.getLocalHost();
System.out.println(add);
System.out.println(add.getHostName());//计算机名
System.out.println(add.getHostAddress());//计算机IP地址
InetAddress baidu = InetAddress.getByName("www.baidu.com");
System.out.println("百度地址:"+baidu.getHostAddress());
System.out.println("百度主机:"+baidu.getHostName());
System.out.println("=================================");
InetAddress[] ids =InetAddress.getAllByName("www.tmall.com");
for (int i = 0; i <ids.length ; i++) {
System.out.println(ids[i]);
}
}
}
package com.cs.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 16:30
**/
public class QQServer {
public static void main(String[] args) {
System.out.println("QQ Server is Running.....");
ServerSocket s = null;
Socket client = null;
try {
s = new ServerSocket(9090);
while (true) {
s.accept();
//一个客户端连接就开两个线程分别处理读和写
new Thread(new ReadThread(client)).start();
new Thread(new WriterThread(client)).start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
*处理读取操作的线程
*/
class ReadThread implements Runnable {
private Socket client = null;
public ReadThread(Socket client) {
this.client = client;
}
@Override
public void run() {
BufferedReader in = null;
try {
while (true) {
//读取客户端数据
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("客户端说:" + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client = null;
}
}
}
}
/*
* 处理写操作的线程
*/
class WriterThread implements Runnable {
private Socket client;
public WriterThread(Socket client) {
this.client = client;
}
@Override
public void run() {
PrintWriter out = null;
try {
out = new PrintWriter(client.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
//从控制台获取输入的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
//向客户端回复信息
System.out.println(reader.readLine());
System.out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client = null;
}
}
}
}
package com.cs.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/**
* com.cs.net.TcpClient01
* com.cs.net.TcpServer01
*
* @author 姚志鸿 2093559162
* @Date 2021/06/08/ 10:48
**/
public class TcpClient01 {
public static void main(String[] args) {
Socket s = null;
OutputStream os = null;
InputStream is = null;
try {
s = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
os = s.getOutputStream();
os.write("我是客户端xxx,请多指教!".getBytes());
//告诉服务端我已传输完成
s.shutdownOutput();
//得到返回的输入流
is = s.getInputStream();
//从输入流解析成数据
byte[] bytes = new byte[128];
int len;
while ((len = is.read(bytes)) != -1) {
String str = new String(bytes, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cs.net;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/08/ 11:05
**/
public class TcpClient02 {
public static void main(String[] args) {
Socket s = null;
FileOutputStream fos = null;
InputStream is = null;
try {
s = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
fos = new FileOutputStream(new File("C:\\James.jpg"));
is = s.getInputStream();
byte[] b = new byte[1024];
int len;
while (((len = is.read(b)) != -1)) {
String str = new String(b, 0, len);
fos.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (s != null) {
s.close();
}
if (fos != null) {
fos.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cs.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author 姚志鸿 2093559162
* 客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端
* @Date 2021/06/09/ 9:53
**/
public class TcpClient03 {
public static void main(String[] args) {
Socket s = null;
OutputStream os = null;
InputStream is = null;
try {
s = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
os = s.getOutputStream();
os.write("abcdefgh".getBytes());
is = s.getInputStream();
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.println("我是客户端,接收到来自服务端的返回数据:" + str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.cs.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* com.cs.net.TcpClient01
* com.cs.net.TcpServer01
* @author 姚志鸿 2093559162
* @Date 2021/06/08/ 10:38
**/
public class TcpServer01 {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os =null;
try {
//1:创建ServerSocket对象
ss = new ServerSocket(9090);
//2:监听并接受此套接字的链接
s = ss.accept();
//3:通过监听,得到输入流
is = s.getInputStream();
//4:从输入流解析成1数据
byte[] bytes = new byte[128];
int len;
while ((len = is.read(bytes)) != -1) {
String str = new String(bytes, 0, len);
System.out.println(str);
}
os=s.getOutputStream();
os.write("我已收到你的消息".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (ss != null) {
ss.close();
}
if (s != null) {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.cs.net;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 1. 客户端读取图片并发送给服务端,服务端保存图片到本地。并返回“发送成功”给客户端。并关闭相应的连接。
* 做一个上传图片的服务器,这个服务器是对应的多客户端,不知道客户端什么上 传图片,也可能是同时多客户端上传图片。
*
* @author 姚志鸿 2093559162
* @Date 2021/06/08/ 11:05
**/
public class TcpServer02 {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
FileInputStream fis = null;
OutputStream os = null;
try {
ss = new ServerSocket(9090);
s = ss.accept();
fis = new FileInputStream(new File("D:\\yaozhihong\\yzh\\图片及视频\\壁纸\\james\\James.jpg"));
os = s.getOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = fis.read(b)) != -1) {
os.write(b, 0, len);
s.shutdownOutput();
}
} catch (
FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.cs.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 9:58
**/
public class TcpServer03 {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(9090);
s = ss.accept();
is = s.getInputStream();
byte[] b = new byte[1024];
int len;
String str = null;
while ((len = is.read(b)) != -1) {
str = new String(b, 0, len);
str = str.toUpperCase();
System.out.println("我是服务端,收到客户端的信息:" + str);
}
os = s.getOutputStream();
os.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.cs.thread;
public class TestCase01 {
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/5 0005 15:06
**/
public class TestCase02 {
//主线程
public static void main(String[] args) {
System.out.println("main方法。。。。。。。");
Demo demo = new Demo();
//demo.run();
demo.start();
for (int i = 0; i < 100; i++) {
System.out.println("Main Running...." + i);
}
}
}
class Demo extends Thread {
public void run() {
System.out.println("Demo的run()方法。。。。");
for (int i = 0; i < 60; i++) {
System.out.println("Demo running.....");
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/5 0005 14:59
**/
public class TestCase03 {
public static void main(String[] args) {
PrintNum p1 = new PrintNum("线程1");
PrintNum p2 = new PrintNum("线程2");
p1.start();
p2.start();
}
}
class PrintNum extends Thread {
public void run() {
//子程序的运行代码
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + "********" + i);
}
}
}
public PrintNum(String name) {
super(name);
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/5 0005 15:06
**/
public class TestCase04 {
public static void main(String[] args) {
PrintNum1 p1 = new PrintNum1();
//P1.run();
//开启一个线程必须要执行Thread类中的start()方法
Thread t1 = new Thread(p1);
t1.setPriority(Thread.NORM_PRIORITY);
t1.setDaemon(true); //把用户线程变成守护线程
t1.setName("aaaa");
t1.start(); //开启一个线程
Thread t2 = new Thread(p1);
t2.setPriority(Thread.NORM_PRIORITY);
t1.setName("bbbb");
t1.start(); //开启一个线程
}
}
class PrintNum1 implements Runnable {
@Override
public void run() {
}
}
package com.cs.thread;
/**
* 模拟火车站三个售票窗口
*
* @author 姚志鸿
* @Date 2021/6/5 0005 16:11
**/
public class TestCase05 {
public static void main(String[] args) {
window w = new window();
Thread t1 = new Thread(w);
t1.setName("窗口1");
Thread t2 = new Thread(w);
t1.setName("窗口2");
Thread t3 = new Thread(w);
t1.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class window implements Runnable {
static int ticket = 100;
@Override
public void run() {
while (true) {
//模拟高并发
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread() + "售票,票号:" + ticket--);
} else {
break;
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/5 0005 16:53
**/
public class TestCase06 {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
class Thread1 extends Thread {
public void run() {
for (int i = 2; i <= 100; i += 2) {
System.out.println("i=" + i);
}
}
}
class Thread2 extends Thread {
public void run() {
for (int j = 1; j <= 100; j += 2) {
System.out.println("j=" + j);
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/7 0007 14:18
**/
public class TestCase07 {
public static void main(String[] args) {
window1 w = new window1();
Thread t1 = new Thread(w);
t1.setName("窗口1");
Thread t2 = new Thread(w);
t1.setName("窗口2");
Thread t3 = new Thread(w);
t1.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class window1 implements Runnable {
static int ticket = 100;
@Override
public void run() {
while (true) {
//模拟高并发
synchronized (this){
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread() + "售票,票号:" + ticket--);
} else {
break;
}
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/7 0007 14:21
**/
public class TestCase08 {
public static void main(String[] args) {
Window2 t1 = new Window2("窗口1");
Window2 t2 = new Window2("窗口2");
Window2 t3 = new Window2("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window2 extends Thread {
static int ticket = 100;
static Object obj = new Object();
public Window2(String name) {
super(name);
}
@Override
public void run() {
while (true) {
//模拟高并发
/**
* synchronized要对同一个对象加锁,才能锁得住
*/
//synchronized (obj) { 在对象上加锁
synchronized (Window2.class) { //在类上面加锁
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread() + "售票,票号:" + ticket--);
} else {
break;
}
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/7 0007 14:34
**/
public class TestCase09 {
public static void main(String[] args) {
Window3 t1 = new Window3("窗口1");
Window3 t2 = new Window3("窗口2");
Window3 t3 = new Window3("窗口3");
t1.start();
t2.start();
t3.start();
}
}
class Window3 extends Thread {
static int ticket = 100;
static Object obj = new Object();
public Window3(String name) {
super(name);
}
@Override
public void run() {
while (true) {
synchronized (this) {
Window3.show();
}
}
}
//在方法上加锁
private static synchronized void show() {
if (ticket > 0) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticket > 0) {
System.out.println(Thread.currentThread() + "售票,票号:" + ticket--);
} else {
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* 单例模式--懒汉式
* @Date 2021/6/7 0007 14:45
**/
public class TestCase10 {
public static void main(String[] args) {
Singleton s = Singleton.getsingleton();
System.out.println(s);
System.out.println("===========");
Singleton s1 = Singleton.getsingleton();
System.out.println(s1);
System.out.println(s == s1);
}
}
//单例模式也就是一个类只能有一个对象
class Singleton {
private static Singleton s = new Singleton();
private Singleton() {
}
private static Singleton sg = null;
public static Singleton getsingleton() {
synchronized (Singleton.class) {
if (sg == null) {
sg = new Singleton();
}
}
return sg;
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* 银行有一个账户。有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额。
* 问题:该程序是否有安全问题,如果有,如何解决?
* @Date 2021/6/7 0007 14:55
**/
public class TestCase11 {
public static void main(String[] args) {
Money money = new Money(0);
Person p1 = new Person(money);
Person p2 = new Person(money);
p1.setName("1");
p2.setName("2");
p1.start();
p2.start();
}
}
class Money {
private double balance; //余额
public Money(double balance) {
this.balance = balance;
}
//存钱(在方法上上锁)
public synchronized void addMoney(double atm) {
if (atm > 0) {
balance += atm;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "存钱成功,余额为:" + balance);
}
}
}
class Person extends Thread {
private Money money;
public Person(Money money) {
this.money = money;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
money.addMoney(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* 线程的死锁
* @Date 2021/6/7 0007 15:44
**/
public class TestCase12 {
static StringBuffer sb1 = new StringBuffer();
static StringBuffer sb2 = new StringBuffer();
}
package com.cs.thread;
/**
* @author 姚志鸿 让甲乙两个线程交替打印0-100的数字
* @Date 2021/6/7 0007 15:49
*/
public class TestCase13 {
public static void main(String[] args) {
PrintNum2 p = new PrintNum2();
Thread t1 = new Thread(p);
t1.setName("甲");
Thread t2 = new Thread(p);
t2.setName("乙");
t1.start();
t2.start();
}
}
class PrintNum2 implements Runnable {
int num = 0;
@Override
public void run() { /* TODO Auto-generated method stub*/
while (true) synchronized (this) {
this.notify();
if (num <= 100) {
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
/* TODO Auto-generated catch block*/
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "===" + num);
num++;
} else break;
try {
this.wait();
} catch (InterruptedException e) {
/* TODO Auto-generated catch block*/
e.printStackTrace();
}
}
}
}
package com.cs.thread;
/**
* @author 姚志鸿
* @Date 2021/6/7 0007 16:06
**/
public class TestCase14 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Clerk clerk = new Clerk();
//生产者线程
Producer p = new Producer(clerk);
//生产者线程
Consumer c = new Consumer(clerk);
Thread p1 = new Thread(p);//生产者线程
p1.setName(" 生产者A ");
Thread p2 = new Thread(p); //生产者线程
p2.setName(" 生产者B ");
Thread c1 = new Thread(c);//消费者线程
c1.setName(" 消费者 ");
p1.start();
p2.start();
c1.start();
}
}
//店员
class Clerk{
int product;
//生产产品
public synchronized void addProduct() {
if(product >= 20) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
product++;
System.out.println(Thread.currentThread().getName() +
"生产第 " + product + " 产品 ");
notifyAll();
}
}
//消费产品
public synchronized void subProduct() {
if(product <= 0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
System.out.println(Thread.currentThread().getName() +
"消费第 " + product + " 产品 ");
product--;
notifyAll();
}
}
}
//生产者
class Producer implements Runnable{
Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("开始生产产品");
while(true) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.addProduct();
}
}
}
//消费者
class Consumer implements Runnable{
Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("开始消费产品");
while(true) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clerk.subProduct();
}
}
}
package com.cs.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 16:11
**/
public class Receiver {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9090);
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, 0, b.length);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.cs.udp;
import java.io.IOException;
import java.net.*;
/**
* @author 姚志鸿 2093559162
* @Date 2021/06/09/ 16:10
**/
public class Send {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
byte[] b = "您好!我是要发送的数据".getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length,
InetAddress.getByName("127.0.0.1"), 9090);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.cs.udp;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
//URL:统一资源定位符,一个URL的对象,对应着互联网上一个资源。
//我们可以通过URL的对象调用其相应的方法,将此资源读取(“下载”)
public class TestURL {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
// 1.创建一个URL的对象
URL url = new URL("http://127.0.0.1:8080/examples/HelloWorld.txt?a=b");// File file = new File("文件的路径");
/*
* public String getProtocol( ) 获取该URL的协议名 public String getHost( ) 获取该URL的主机名
* public String getPort( ) 获取该URL的端口号 public String getPath( ) 获取该URL的文件路径
* public String getFile( ) 获取该URL的文件名 public String getRef( ) 获取该URL在文件中的相对位置
* public String getQuery( ) 获取该URL的查询名
*/
// System.out.println(url.getProtocol());
// System.out.println(url.getHost());
// System.out.println(url.getPort());
// System.out.println(url.getFile());
// System.out.println(url.getRef());
// System.out.println(url.getQuery());
// 如何将服务端的资源读取进来:openStream()
InputStream is = url.openStream();
byte[] b = new byte[20];
int len;
while ((len = is.read(b)) != -1) {
String str = new String(b, 0, len);
System.out.print(str);
}
is.close();
// 如果既有数据的输入,又有数据的输出,则考虑使用URLConnection
URLConnection urlConn = url.openConnection();
InputStream is1 = urlConn.getInputStream();
FileOutputStream fos = new FileOutputStream(new File("abc.txt"));
byte[] b1 = new byte[20];
int len1;
while ((len1 = is1.read(b1)) != -1) {
fos.write(b1, 0, len1);
}
fos.close();
is1.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment