发布网友 发布时间:2022-04-23 07:44
共1个回答
热心网友 时间:2022-06-17 21:15
我给你一个吧,写得比较简单,再实现什么功能,自己修改吧
server
=====
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(9999);
while(true) {
Socket s = server.accept();
InputStream in = s.getInputStream();
DataInputStream dis = new DataInputStream(in);
int a = dis.readInt();
int b = dis.readInt();
int sum = a+b;
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(sum);
dos.flush();
s.close();
}
}
}
=====
client
===========
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestClient {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost",9999);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(10);
dos.writeInt(20);
dos.flush();
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
System.out.println(dis.readInt());
socket.close();
}
}