Java Socket类使用
使用基于TCP的通信,编写一个客户/服务器程序,客户端将正方形的长发送给服务器端,服务器端计算正方形的周长和面积返回给客户端。其中正方形的长通过键盘输入。
结果如图
这里是客户端的控制台
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/962a70e160555411b217872cac83fa2d.png)
这里是服务器的控制台
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d87391bc408452f589cb0d2837bd8fb7.png)
这里是客户端代码
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class SocketTestClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1",10004);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
System.out.println("这是一个计算正方形周长和面积的服务:");
System.out.print(" 请输入正方形的长:");
Scanner scanner = new Scanner(System.in);
String nextData = scanner.next();
out.write(nextData.getBytes());
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
socket.close();
}catch(IOException e){
System.out.println("Error"+e);
}
}
}
这里是服务器代码
public class SocketTestServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(10004);
Socket socketClient = serverSocket.accept();
String ip = socketClient.getInetAddress().getHostAddress();
System.out.println(ip+"...connect");
System.out.println("连接成功");
InputStream in = socketClient.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String data = new String(buf, 0, len);
System.out.println("边长为:"+data);
double squarelength = Double.parseDouble(data);
double perimeter = squarelength * 4;
double area = squarelength*squarelength;
String result = "边长为:"+data+"的正方形,周长为:"+perimeter+",面积为:"+area+"。";
OutputStream out = socketClient.getOutputStream();
out.write(result.getBytes());
socketClient.close();
serverSocket.close();
}catch(Exception e) {
System.out.println("Error"+e);
}
}
}