写好了,有什么问题请追问。
客户端:
import java.net.*;
import java.io.*;
public class TestSocketClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 5566);
System.out.println("请输入计算式:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1 = br.readLine();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF(s1);
dos.flush();
double s = dis.readDouble();
System.out.println("计算结果:" + s);
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("连接出错");
System.exit(-1);
}
}
}
服务器端:
import java.net.*;
import java.io.*;
public class TestSocketServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5566);
Socket socket = ss.accept();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
String s = null;
if ((s = dis.readUTF()) != null) {
System.out.println("接收到的算式:" + s);
double result = 0;
String[] sarr1 = s.split("[\\+\\-\\*\\/]");
double a = Double.parseDouble(sarr1[0].trim());
double b = Double.parseDouble(sarr1[1].trim());
String[] sarr2 = s.split("^(-?\\d+)(\\.\\d+)?");
char c = sarr2[1].trim().charAt(0);
switch (c) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
break;
}
dos.writeDouble(result);
dos.flush();
}
dis.close();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
追问这个是不是还要新建个TestSocketClient的类说明是公共的啊?怎么弄呢?
追答这两个类放到两个java文件里运行,一个TestSocketClient.java 一个 TestSocketServer.java
追问不用倒包吧?
追答不用。
本回答被提问者采纳