用套接字實現(xiàn)客戶——服務(wù)器交互計算薇搁,客戶端輸入三角形三邊長并發(fā)送給服務(wù)器,服務(wù)器把計算出的三角形面積返回給客戶。
TCPserver.java
package test9;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPserver {
public static final int NUM = 3;
public static void main(String args[]){
TCPserver TCPserver = new TCPserver();
try {
ServerSocket server = null;
try {
server = new ServerSocket(6666);
} catch (Exception e) {
e.printStackTrace();
}
Socket socket = null;
try {
socket = server.accept();
} catch (Exception e) {
e.printStackTrace();
}
String line = "";
double a[] = new double[NUM];
BufferedReader is = new BufferedReader(new InputStreamReader
(socket.getInputStream()));
System.out.println("從客戶端接收三角形的三條邊:");
for (int i = 0; i < a.length; i++) {
line = is.readLine();
a[i] = Double.parseDouble(line);
}
System.out.println("三角形的面積是:" + TCPserver.countarea(a));
is.close();//關(guān)閉讀取流
socket.close();//關(guān)閉Socket
server.close();//關(guān)閉ServerSocket
} catch (Exception e) {
e.printStackTrace();
}
}
//計算三角形面積的方法
public double countarea(double a[]){
double area = 0.0;
double temp = 0.0;
double aside = 0.0;
double bside = 0.0;
double cside = 0.0;
aside = a[0];
bside = a[1];
cside = a[2];
temp = a[0] + a[1] + a[2];
temp = temp / 2;
area = Math.sqrt(temp * (temp - aside) * (temp - bside) * (temp - cside));
return area;
}
}
TCPclient.java
package test9;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TCPclient {
public static final int NUM = 3;
public static void main(String args[]){
try {
Socket socket = new Socket("127.0.0.1", 6666);
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
PrintWriter os = new PrintWriter(socket.getOutputStream());
System.out.println("從客戶端接收三角形的三條邊發(fā)送到服務(wù)器:");
System.out.println("請輸入3條邊:");
String readline = "";
for (int i = 0; i < NUM; i++) {
os.flush();
readline = sin.readLine();
os.println(readline);
}
os.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 兩者放到同一目錄下
- 先編譯TCPserver.java
- 在編譯運行TCPclient.java
- 依次輸入三角形三條邊的長
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者