服务端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) throws IOException {
System.out.println("---------------------服务开启-----------------------");
// 建立端口,监听新的请求
ServerSocket ss = new ServerSocket(9856);
Socket s = ss.accept();
// 读取客户端输入的信息
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
// 进行输出
while ((line = br.readLine()) != null) {
System.out.println("-----客户端输入的信息是-----");
System.out.println(line);
}
s.close();
}
}
客户端代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
// 建立连接
Socket s = new Socket("127.0.0.1", 9856);
// 读取键盘输入流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 端口输出
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line = null;
// 输入886结束输出
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
}
bw.write(line);
bw.newLine();
bw.flush();
}
s.close();
}
}
测试结果