server:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class SocketServer {
private static boolean flag = true;
private static class SocketClient implements Runnable {
private Socket client = null;
private InputStream inputStream = null;
private Scanner scanner = null;
private PrintStream printStream = null;
public SocketClient(Socket client) {
try {
this.client = client;
this.inputStream = client.getInputStream();
this.scanner = new Scanner(this.inputStream);
scanner.useDelimiter("\n");
this.printStream = new PrintStream(this.client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (flag) {
if (scanner.hasNext()) {
String str = scanner.next().trim();
if ("bye".equalsIgnoreCase(str)) {
flag = false;
} else {
this.printStream.println("response: " + str);
}
} else {
try {
printStream.close();
scanner.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(8888);
System.out.println("等待客户端链接。");
while (flag) {
Socket client = server.accept();
new Thread(new SocketClient(client)).start();
}
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class SocketClient {
public static void main(String[] args) throws IOException {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
Socket client = new Socket("localhost", 8888);
InputStream inputStream = client.getInputStream();
Scanner scanner = new Scanner(inputStream);
scanner.useDelimiter("\n");
PrintStream out = new PrintStream(client.getOutputStream());
boolean flag = true;
while (flag){
System.out.println("请输入要输入的内容: ");
String line = bufferedReader.readLine().trim();
out.println(line);
if(scanner.hasNext()){
System.out.println(scanner.next());
}
if("bye".equalsIgnoreCase(line)){
flag = false;
}
}
scanner.close();
out.close();
inputStream.close();
client.close();
}
}
|