本帖最后由 魏先勇 于 2013-8-15 19:31 编辑
如下代码,我对照了一下毕老师的代码,只是毕老师用的是字节流,我这里转换成了字符流,其他没什么不同,但是当我运行的时候服务端和客户端都得不到结果,求解。- import java.io.*;
- import java.net.*;
- class TcpClient2
- {
- public static void main(String[] args) throws Exception
- {
- InetAddress addr = InetAddress.getByName(null);
- Socket s = new Socket(addr, 10001);
- //这里把BufferedWriter换成PrintWriter程序就能执行,求解是我代码错误还是不能使用BufferedWriter。
- BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(
- s.getOutputStream()));
- bufw.write("hello,server!");
- bufw.flush();
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- s.getInputStream()));
- String str = bufr.readLine();
- System.out.println(str);
- s.close();
- }
- }
- class TcpServer2
- {
- public static void main(String[] args) throws Exception
- {
-
- ServerSocket ss = new ServerSocket(10001);
- Socket s = ss.accept();
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- s.getInputStream()));
- String str = bufr.readLine();
- System.out.println(str);
- BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(
- s.getOutputStream()));
- bufw.write(str.toUpperCase());
- bufw.flush();
- s.close();
- ss.close();
-
- }
- }
复制代码 附上可以执行的代码:- import java.io.*;
- import java.net.*;
- class TcpClient2
- {
- public static void main(String[] args) throws Exception
- {
- InetAddress addr = InetAddress.getByName(null);
- Socket s = new Socket(addr, 10001);
- PrintWriter out = new PrintWriter(s.getOutputStream(), true);
- out.println("hello,server!");
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- s.getInputStream()));
- String str = bufr.readLine();
- System.out.println(str);
- s.close();
- }
- }
- class TcpServer2
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10001);
- Socket s = ss.accept();
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- s.getInputStream()));
- String str = bufr.readLine();
- System.out.println(str);
- PrintWriter out = new PrintWriter(s.getOutputStream(), true);
- out.println(str.toUpperCase());
- s.close();
- ss.close();
- }
- }
复制代码 |