本帖最后由 fighting 于 2013-3-30 23:04 编辑
上午看一哥们问了一个socket的问题,我试了试发现些问题:
当在一端将数据写出,在另一端读取数据时,总是提示连接被重置,
哪位能说明一下socket的实现原理,以及出现这种情况的原因。- class TextClient {
- public static void main(String[] args) throws Exception {
- Socket s = new Socket("localhost", 10006);
- OutputStream os = s.getOutputStream();
- os.write("hahahahaha".getBytes());
-
- os.close();
- s.close(); //如果这里不关闭的话,在服务端问题提示连接被重置
- }
- }
复制代码- class TextServer {
- public static void main(String[] args) throws Exception {
- ServerSocket ss = new ServerSocket(10006);
- Socket s = ss.accept();
-
- InputStream is = s.getInputStream();
-
- byte[] buffer = new byte[1024];
- int length = -1;
- while(-1 != (length = is.read(buffer))){
- System.out.println(new String(buffer, 0, length));
- }
-
- ss.close();
- s.close();
- }
- }
复制代码 |