TCP
模拟报名
//服务器端
public class MyServer {
public static void main(String[] args) throws Exception {
try (ServerSocket ss = new ServerSocket(10000)) {
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println("欢迎咨询");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ss1 = br.readLine();
System.out.println(ss1);
ps.println("满了,换个班吧");
ss1 = br.readLine();
System.out.println(ss1);
br.close();
ps.close();
s.close();
}
}
}
//客户端
public class MyClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost",10000);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ss = br.readLine();
System.out.println(ss);
PrintStream ps = new PrintStream(os);
ps.println("报名java班");
ss=br.readLine();
System.out.println(ss);
ps.println("好吧,再见");
br.close();
ps.close();
s.close();
}
}
从properties文件读取
//客户端
public class MyClient {
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket("localhost", 10000);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);) {
String ss = "";
while (ss != null | ss.trim().length() < 1) {
ss = br1.readLine();
}
ps.println(ss.trim());
ss = br2.readLine();
System.out.println(ss);
}
}
}
//服务器端
public class MySever {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.load(MySever.class.getResourceAsStream("dict.properties"));
try (ServerSocket ss = new ServerSocket(10000);
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);) {
String str = br.readLine();
String res = "没有找到";
if (str != null && str.trim().length() > 0) {
if (p.containsKey(str))
res = p.getProperty(str);
}
ps.println(res);
}
}
}
向服务器上传图片
//服务器端
public class MyServer {
public static void main(String[] args) throws Exception {
try (ServerSocket ss = new ServerSocket(10000);
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os)) {
String str = br.readLine();
if (str.startsWith("put ")) {
String fileName = str.substring(str.lastIndexOf(" ") + 1, str.lastIndexOf(","));
String slen = str.substring(str.lastIndexOf(",") + 1);
long length = 0;
try {
length = Long.parseLong(slen.trim());
} catch (Exception e) {
length = -1;
}
if (length <= 0)
throw new RuntimeException("上传失败");
ps.println("ok");
long size = 0;
fileName = fileName.substring(0, fileName.lastIndexOf(".")) + (new Date().getTime())
+ fileName.substring(fileName.lastIndexOf("."));
OutputStream os2 = new FileOutputStream("photo/" + fileName);
byte[] buffer = new byte[8192];
int len = 0;
while ((len = is.read(buffer)) > 0) {
os2.write(buffer, 0, len);
size += len;
if (length == size)
break;
}
os2.close();
if (length == size) {
ps.println("上传成功!");
} else {
File file = new File("photo/" + fileName);
if (file.exists())
file.delete();
ps.println("上传失败!");
}
}
}
}
}
//客户端
public class MyClient {
public static void main(String[] args) throws Exception {
try (BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
Socket s = new Socket("localhost", 10000);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
BufferedReader br = new BufferedReader(new InputStreamReader(is));) {
String fileName = br1.readLine();
String newFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
File file = new File(fileName);
boolean flag = true;
if (!file.exists() || file.length() > 2 * 1024 * 1024)
flag = false;
String fileExtendName = fileName.substring(fileName.lastIndexOf("."));
if (!".jpg".equals(fileExtendName))
flag = false;
if (!flag) {
System.out.println("上传的文件不合法");
System.exit(1);// 直接退出应用,如果0表示正常退出,非0表示非正常退出
}
ps.println("put " + newFileName + "," + file.length());
String str = br.readLine();
if ("ok".equalsIgnoreCase(str)) {
InputStream is2 = new FileInputStream(fileName);
byte[] buffer = new byte[8192];
int len = 0;
while ((len = is2.read(buffer)) > 0) {
ps.write(buffer, 0, len);
}
ps.flush();
str = br.readLine();
System.out.println(str);
is2.close();
}
}
}
}
UDP
UDP网络通信的发包过程
1、使用DatagramSocket()创建一个数据包套接字。
2、使用DatagramPacket(byte[]buf, int offset, int length, InetAddress address, int port)创建要发送的数据包。
3、使用DatagramSocket类的send()方法数据包
UDP网络通信的收包过程
1、使用DatagramSocket(int)创建一个数据包套接字,绑定到指定的端口。
2、使用DatagramPacket(byte[]buf,int length)创建字节数组来接收数据包.
3、使用DatagramSocket类的receive()方法接收UDP
获取的数据实际上就存储在创建空包的数组种,转换显示时建议设置长度
System.out.println(dp.getLength()); //数据的具体长度
String str=new String(buffer,0,dp.getLength());
一般来说UDP协议的最大数据包的长度64k
多播或者组播的实现
- 真正聊天室的实现原理
- MulticastSocket可以将数据报以广播的方式发送给加入指定组的所有客户端
- 组播是指把信息同时传递给一组目的地址。它使用的策略是最高效的,因为消息在每条网络链路上只需传递一次,且只有在链路分叉的时候,消息才会被复制。与多播相比,常规的点到单点传递被称作单播。当以单播的形式把消息传递给多个接收方时,必须向每个接收者都发送一份数据副本。由此产生的多余副本将导致发送方效率低下,且缺乏可扩展性。不过,许多流行的协议——例如XMPP,用限制接收者数量的方法弥补了这一不足
//接收端
public class Recv {
public static void main(String[] args) throws Exception{
//打开监听端口,等待发送方的发送数据。注意这里不会建立连接
DatagramSocket ds = new DatagramSocket(9000);
//创建空数据报用于接收发送的数据,注意字节数组的长度不能小于需要接收的内容长度,否则会有截取部分的问题
byte[] buffer = new byte[8192];
DatagramPacket dp = new DatagramPacket(buffer,buffer.length);
//阻塞当前线程等待发送的数据到达,接收后数据会填充到空数据报种
ds.receive(dp);
System.out.println(dp.getAddress()); //发送方的IP地址
System.out.println(dp.getPort()); //发送方的端口号
byte[] data = dp.getData(); //接收到的数据
System.out.println(new String(data));
ds.close();
}
}
//发送端
public class Sender {
public static void main(String[] args) throws Exception {
// 随意打开一个空闲端口,用于发送数据报
DatagramSocket ds = new DatagramSocket();
// 需要发送的具体数据
String str = "小日子";
byte[] arr = str.getBytes();
// 构建对应的数据报
// 参数1是发送的具体数据,参数2是具体数据的长度,参数3是接收方的IP地址,参数4是接收方的端口号
DatagramPacket dp = new DatagramPacket(arr, arr.length,InetAddress.getByName("localhost"),9000);
ds.send(dp);
ds.close();
}
}