📄 serverthread.java
字号:
import java.net.*;
import java.io.*;
/**
* 这个类是服务器端的线程类,
* 通过继承Thread类,重写run方法来实现
* @author 刘之岗
*
*/
public class ServerThread extends Thread{
Socket socket;
DataOutputStream dos;
DataInputStream dis;
double result;
double x;
double y;
public ServerThread(Socket socket){
this.socket = socket;
}
/**
* 本方法重写Thread类的run方法,
* 用来接受客户段的数据,调用receive方法接受数据,
* 调用calculate方法结算此点到原点的距离
* 调用writeDouble方法将结果写入客户端
*/
public void run(){
try {
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
receive();
result = calculate(x,y);
dos.writeDouble(result);
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(dis != null){
try {
dis.close();
dis = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(dos != null){
try {
dos.flush();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 本方法用来接受客户断的数据,分别保存在x,y中,
public void receive(){
try {
x = dis.readDouble();
y = dis.readDouble();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param x 客户端写入的x坐标的值
* @param y 客户端写入的y坐标的值
* @return 坐标(x,y)距离原点的距离
*/
public double calculate(double x, double y){
double temp = x*x + y*y;
return Math.sqrt(temp);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -