Java套接字,客户端和服务器 [英] Java socket , client and server

查看:143
本文介绍了Java套接字,客户端和服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为客户端和服务器建立套接字连接以显示文件列表.但是下面的代码没有从服务器获取任何输入或没有将输出提供给客户端.请帮忙.

I want to do a socket connection for client and server to display the list of files. but below code is not taking any input from server or giving output to client. Please help.

服务器

package javaapplicationthread;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;



public class zs {
  public static int reads,red;  
    public static void main(String[] args) 
    { 
            int flg=0;

           try{while(true){ 
               ServerSocket serverSocket = new ServerSocket(1312);
           Socket clientSocket = serverSocket.accept();

                         BufferedReader bufferedReader;
       PrintWriter outk=new PrintWriter(clientSocket.getOutputStream(),true);

       bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

       String inputLine = bufferedReader.readLine();
       System.out.println("input is"+ inputLine);
       outk.write("abc");

         File inputFolder = new File(inputLine);
    System.out.println("control is being sent to traverse");
         traverse(inputFolder, "");

    }
           }            
       catch (IOException ex) {
                  System.out.println("my exception is"+ex)
            System.out.println(leftIndent + parentNode.getName());
        }

    }}

推荐答案

在客户端中,当您执行redd = b.readLine();时,您要求读取整行.但是在服务器中,您没有发送整行:您只要求它写三个字符:

In the client, when you do redd = b.readLine(); you are asking to read an entire line. But in the server you haven't sent an entire line: you've only asked it to write three characters:

outk.write("abc");

但是,这三个字符都不发送,因为PrintWriter会临时缓冲它们.要解决此问题,请将该行更改为:

None of those three characters is actually sent, however, because the PrintWriter buffers them temporarily. To fix it, change that line to:

outk.println("abc");

或者:

outk.write("abc\n");
outk.flush();

更改之后,客户端成功显示:result is abc.

After that change, the client successfully displays: result is abc.

它没有给出任何错误

it is not giving any errors

它们都给出错误... readLine调用失败时,客户端引发异常.当服务器开始while(true)循环的下一次迭代并尝试重新创建它仍在使用的套接字时,服务器将引发异常.您可能想将ServerSocket的创建移到while循环之外.

They're both giving errors... The client throws an exception when the readLine call fails. The server throws an exception when it begins the next iteration of the while(true) loop and tries to recreate the socket it is still using. You probably want to move the creation of the ServerSocket outside the while loop.

这篇关于Java套接字,客户端和服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆