用java编写Client和Server程序,实现Client和Server的数据通信。
用java编写Client和Server程序,实现Client和Server的数据通信。要求1服务器ip地址为localhost,服务端口为2408要求2服务器可持续接受...
用java编写Client和Server程序,实现Client和Server的数据通信。要求1服务器ip地址为localhost,服务端口为2408
要求2服务器可持续接受数据“Hellow World!”,并打印到控制台。 展开
要求2服务器可持续接受数据“Hellow World!”,并打印到控制台。 展开
1个回答
展开全部
服务端代码:
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
public static void main(String[] args) throws UnknownHostException, IOException {
ServerSocket server = new ServerSocket(2408, 5, InetAddress.getByName("localhost"));
while (true) {
// 等待客户端的连接
Socket clientSocket = server.accept();
// 为每个连接的客户端分配一个线程,与客户端通信
new Thread(new ClientThread(clientSocket)).start();
}
}
}
class ClientThread implements Runnable {
private Socket clientSocket;
public ClientThread(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
InputStream input = clientSocket.getInputStream();
byte[] buffer = new byte[1024];
boolean exit = false;
while(!exit) {
int len = input.read(buffer);
String message = new String(buffer, 0, len);
if ("bye".equals(message)) {
exit = true;
}
System.out.println(clientSocket.getRemoteSocketAddress() + ": " + message);
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端代码:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Scanner scanner = new Scanner(System.in);
Socket socket = new Socket(InetAddress.getByName("localhost"), 2408);
OutputStream output = socket.getOutputStream();
boolean exit = false;
while (!exit) {
String message = scanner.nextLine();
if ("bye".equals(message)) {
exit = true;
}
byte[] data = message.getBytes();
output.write(data);
output.flush();
}
socket.close();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询