首先,对本周所学进行总结:
基础知识:1.集合框架(容器):Collection接口是集合框架的顶层接口,其子接口有
(1)List接口(ArrayList,LinkedList,Vector)有序集合,允许重复元素
(2) Set接口(HahSet,TreeSet)无序集合,不允许出现重复元素
(3) Map接口(HashMap,TreeMap)
高级知识:2.IO流
(1)流的分类(根据流的性质划分)
- 按流向分输入(input)/输出流(output)
- 按类型分字符(以reader或writer结尾)/字节(以stream结尾)流
- 按功能分节点流(低级流:直接与输入、输出源对接)/处理流(高级流:建立在低级流的基础上:转换流)
(2)系统内置类
File类的用法,
- BufferedInputStream/BufferedOutputStream
- BufferedReader/BufferedWriter
-InputStreamReader/OutputSreamWriter(转换流)
-PrintStream/PrintWriter(打印流)
-RandomAccessFile类(随机文件访问)
(3)对象序列化(serializble接口)transient:关键字,可将其修饰的元素不进行序列化
ObjectOutputStream/ObjectInputStream
3.网络编程
(1)网络协议(TCP/UDP)
(2)Socket通信(基于两种网络协议)
4.多线程:继承Thread类或实现Runnable接口。
接下来是基于多线程与IO流所写的聊天室代码,根据UDP协议:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class FeiQSender extends Thread{
@Override
public void run() {
String ip = "192.168.4.138";
DatagramSocket ds = null;
try {
ds = new DatagramSocket(8888);
} catch (SocketException e) {
e.printStackTrace();
}
DatagramPacket dp = null;
byte[] b =null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg = "";
try {
while(!(msg = br.readLine()).equals("quit")) {
//发送消息
b = msg.getBytes();
dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName(ip), 6667);
ds.send(dp);
//接收
ds.receive(dp);
msg = new String(dp.getData(),0,dp.getLength());
System.out.println(dp.getAddress().getHostAddress()+":"+msg);
}
} catch (IOException e) {
e.printStackTrace();
}
ds.close();
}
public static void main(String[] args) throws IOException {
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class FeiQReciver {
public static void main(String[] args) throws IOException {
String ip = "192.168.4.138";
DatagramSocket ds = new DatagramSocket(6667);
byte[] b = new byte[112];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramPacket dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName(ip), 8888);
ds.receive(dp);
String msg = new String(dp.getData(),0,dp.getLength());
while (dp.getData() != null) {
msg = new String(dp.getData(), 0, dp.getLength());
System.out.println("Sender:" + msg);
msg = br.readLine();
b = msg.getBytes();
dp = new DatagramPacket(b, 0, b.length, InetAddress.getByName(ip), 8888);
ds.send(dp);
ds.receive(dp);
}
ds.close();
}
}