1-1 假设Tom和Jerry利用Java UDP进行聊天,请为他们编写程序。具体如下:
(1)、Tom和Jerry聊天的双方都应该具有发送端和接收端;
(2)、利用DatagramSocket与DatagramPacket;
(3)、实现 java.lang.Runnable类,重写 run()方法。
我采用了四个java文件实现,也可创建内部内实现多线程:
JerryClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import .DatagramPacket;
import .DatagramSocket;
import .InetAddress;
public class JerryClient {
public static void main(String[] args) throws IOException {
/*RunnableJerry jerry = new RunnableJerry();
jerry.run();*/
new Thread(new RunnableJerry()).start();
//System.out.println("send=======start");
JerryClient jerryClient = new JerryClient();
jerryClient.send();
//System.out.println("send=====end");
}
public void send() throws IOException {
DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));//从键盘上面输入文本
String line = null;
while((line=bufr.readLine())!=null)//当输入不为空时
{
if("byebye".equals(line))//当输入为byebye时退出程序
break;
//确定好数据后,并把数据封装成数据包
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length, InetAddress.getByName("localhost"),52014);//发送至指定IP,指定端口
ds.send(dp);//通过send方法将数据包发送出去
}
}
public void receive() throws IOException {
//@SuppressWarnings("resource")
DatagramSocket ds = new DatagramSocket(52013);//接收端监听指定端口
while(true)
{
//定义数据包,用于存储数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
//通过数据包的方法获取其中的数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println("Tom: "+data);
}
}
}Runnable.java
import java.io.IOException;
public class RunnableJerry implements Runnable{
@Override
public void run() {
JerryClient jerryClient = new JerryClient();
try {
//System.out.println("receive=====start");
jerryClient.receive();
//System.out.println("receive=====end");
} catch (IOException e) {
e.printStackTrace();
}
}
}TomClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import .DatagramPacket;
import .DatagramSocket;
import .InetAddress;
public class TomClient {
public static void main(String[] args) throws IOException {
/*RunnableTom tom = new RunnableTom();
tom.run();*/
new Thread(new RunnableTom()).start();
TomClient tomClient = new TomClient();
tomClient.send();
}
public void send() throws IOException {
DatagramSocket ds = new DatagramSocket();//通过DatagramSocket对象创建udp服务
BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));//从键盘上面输入文本
String line = null;
while((line=bufr.readLine())!=null)//当输入不为空时
{
if("byebye".equals(line))//当输入为byebye时退出程序
break;
//确定好数据后,并把数据封装成数据包
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length, InetAddress.getByName("localhost"),52013);//发送至指定IP,指定端口
ds.send(dp);//通过send方法将数据包发送出去
}
}
public void receive() throws IOException {
//@SuppressWarnings("resource")
DatagramSocket ds = new DatagramSocket(52014);//接收端监听指定端口
while(true)
{
//定义数据包,用于存储数据
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
//通过数据包的方法获取其中的数据
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println("Jerry:"+data);
}
}
}RunnableTom.java
import java.io.IOException;
public class RunnableTom implements Runnable {
@Override
public void run() {
TomClient tomClient = new TomClient();
try {
tomClient.receive();
} catch (IOException e) {
e.printStackTrace();
}
}
}运行效果:

1-2 利用Java Socket编写一个简单的Web服务器,具体如下:
(1)、使用 ServerSocket 监听某一端口,然后等待连接获取 Socket对象;
(2)、创建一个类 HttpServer 继承 java.lang.Thread 类,重写 run()方法,执行浏览器请求;
(3)、获得浏览器请求,解析资源文件路径;
(4)、读取资源文件,响应给浏览器;
(5)、浏览器地址栏输入: http://localhost:8000/index.html;
(6)、效果如下:
需要注意的html位置信息,定义在public static final String ROOT
HttpServer.java
package q2;
import java.io.*;
import .Socket;
public class HttpServer extends Thread{
/**
* web资源根路径
*/
public static final String ROOT = "F:/code/Java_code/StudyCode/NetworkLab/Lab1/src/q2";
/**
* 输入流对象,读取浏览器请求
*/
private InputStream input;
/**
* 输出流对象,响应内容给浏览器
*/
private OutputStream out;
public HttpServer(Socket socket) {
try {
input = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 多线程方法调用
*/
@Override
public void run() {
String filePath = read();
response(filePath);
}
private void response(String filePath) {
File file = new File(ROOT + filePath);
if (file.exists()) {
// 1、资源存在,读取资源
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
StringBuffer result = new StringBuffer();
result.append("HTTP /1.1 200 ok \r\n");
result.append("Content-Type:text/html \r\n");
result.append("Content-Length:" + file.length() + "\r\n");
result.append("\r\n:" + sb.toString());
out.write(result.toString().getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 2、资源不存在,提示 file not found
StringBuffer error = new StringBuffer();
error.append("HTTP /1.1 400 file not found /r/n");
error.append("Content-Type:text/html \r\n");
error.append("Content-Length:20 \r\n").append("\r\n");
error.append("<h1 >File Not Found..</h1>");
try {
out.write(error.toString().getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String read() {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
// 读取请求头, 如:GET /index.html HTTP/1.1
String readLine = reader.readLine();
String[] split = readLine.split(" ");
if (split.length != 3) {
return null;
}
System.out.println(readLine);
return split[1];
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}WebServer.java
package q2;
import java.io.IOException;
import .ServerSocket;
import .Socket;
public class WebServer {
public static void main(String[] args) {
new WebServer().startServer(8000);
}
public void startServer(int port){
try {
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(port);
while(true){
Socket socket = serverSocket.accept();
new HttpServer(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}运行效果:

















