在java Socket编程中(client给server发送一个字符串,再由server返回一个字符串给client)

2024-12-16 07:08:10
推荐回答(3个)
回答1:

SERVER端:
--------------------------------------------------------
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {

private Socket clientSocket;

public Server(Socket clientSocket) {
this.clientSocket = clientSocket;
}

public void run() {

DataInputStream dis = null;
DataOutputStream dos = null;

try {

dis = new DataInputStream(clientSocket.getInputStream());
dos = new DataOutputStream(clientSocket.getOutputStream());

while (true) {
String temp = dis.readUTF();
if ("over".equals(temp)) {
break;
}
dos.writeUTF("from server:" + temp);
}

} catch (Exception e) {
//e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dis != null) {
dos.close();
}

if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Server Thread is shutdown.");
}
}
}

public static void main(String[] args) throws Exception {

ServerSocket ss = new ServerSocket(8008);
while (true) {
Socket clientSocket = ss.accept();
// 针对每个客户端, 启一个Server线程专门处理此客户端的请求。
Server server = new Server(clientSocket);
server.start();
}

}

}

CLIENT端:
----------------------------------------
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {

public static void main(String[] args) throws Exception {

// 输入流1, 从键盘进入Client。
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

Socket clientSocket = new Socket("127.0.0.1", 8008);

// 输入流2, 从服务器端进入Client的流对象。
DataInputStream dis = new DataInputStream(clientSocket.getInputStream());

// 输出流, 从Client出去, 到服务器端。
DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());

while (true) {

// 从键盘输入读取
String msg = br.readLine();

// 将读取信息发送给服务器端
dos.writeUTF(msg);

//输入over退出
if ("over".equals(msg)) {
break;
}

//读取从服务器返回的信息
String temp = dis.readUTF();
System.out.println(temp);
}

br.close();
dis.close();
dos.close();
clientSocket.close();

}

}
--------------------------------------------------------

回答2:

去网上搜吧!很多很多!

回答3:

就是么,好多的,自己搜吧