Server
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
int port = 5000;
ServerSocket server = new ServerSocket(port);
Socket socket = server.accept(); // 可在此及后创建线程实现多客户访问
BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String readLine = null;
while (readLine != "bye"){
readLine = reader.readLine();
System.out.println("客户端:" + readLine);
readLine = systemIn.readLine();
writer.println(readLine);
writer.flush();
}
server.close();
socket.close();
systemIn.close();
reader.close();
writer.close();
}
}
Client
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception{
String ip = "127.0.0.1";
int port = 5000;
Socket socket = new Socket(ip, port);
BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String readLine = null;
while (readLine != "bye"){
readLine = systemIn.readLine();
writer.println(readLine);
writer.flush();
readLine = reader.readLine();
System.out.println("服务器:" + readLine);
}
socket.close();
systemIn.close();
reader.close();
writer.close();
}
}
网友评论