Java基于TCP的Socket编程练习

环境:Notpad ++ 6.0 + JDK 6.0.31

问题:使用套接字编写客户—服务器程序,实现客户—服务器交互计算。客户将三角形3个边的长度发给服务器,服务器把计算出的三角形的面积返回给客户。

 

解决:利用JavaSocket编程。客户端发送数据,服务端接收数据,并进行相应的处理。

代码:

 TcpServer.java

 

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(4700);
			} 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();//关闭读取流
			socket.close();//关闭Socket
			server.close();//关闭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

 

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", 4700);
			BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
			
			PrintWriter os = new PrintWriter(socket.getOutputStream());
			
			System.out.println("从客户端接收三角形的三条边发送到服务器:");
			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();
		}
	}
	
}


 

 

运行:

把客户端程序(TcpClient.java)和服务端程序(TcpServer.java)分别编译,再打开两个Cmd控制台,先运行服务端,再运行客户端,在客户端输入数据,然后就可以在服务端看到结果。

 

运行效果截图:

服务端:

Java基于TCP的Socket编程练习_第1张图片

 

客户端:

Java基于TCP的Socket编程练习_第2张图片

你可能感兴趣的:(Java基于TCP的Socket编程练习)