//服务器
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket server=new ServerSocket(8080);
System.out.println(“服务器开始启动”);
Socket socket=server.accept();
OutputStream os=socket.getOutputStream();
OutputStreamWriter osw=new OutputStreamWriter(os);
BufferedWriter bw=new BufferedWriter(osw);
InputStream is= socket.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
Scanner scanner =new Scanner(System.in);
while(true){
String s=br.readLine();
System.out.println(“有连接进入”+s);
String back=scanner.next();
bw.write(back+”\n”);
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//客户端
public class MyClient {
public static void main(String[] args) {
try {
System.out.println("客户端开始启动");
Socket socket = new Socket("192.168.0.142", 8080);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
Scanner scanner = new Scanner(System.in);
while (true) {
String s = scanner.next();
bw.write(s + "\n");
bw.flush();
String back = br.readLine();
System.out.println("服务器返回数据:" + back);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}