【问题标题】:Simple Java Client/Server Program简单的 Java 客户端/服务器程序
【发布时间】:2010-01-29 20:39:42
【问题描述】:

我正在编写我的第一个 java 客户端/服务器程序,它只是与服务器建立连接,向它发送一个句子,然后服务器将句子全部大写。这实际上是书中的一个示例,当我在同一台机器上运行客户端和服务器并使用 localhost 作为服务器地址时,它运行良好。但是当我将客户端程序放在另一台计算机上时,它会超时并且永远不会与服务器建立连接。我不知道为什么会这样,制作你的第一个客户端/服务器程序并且实际上不能在两台不同的机器上使用它是一种蹩脚的。这是客户端代码:

import java.io.*;
import java.net.*;

public class TCPClient {
    public static void main(String argv[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        Socket clientSocket = new Socket("localhost", 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');
        modifiedSentence = inFromServer.readLine();
        System.out.println(modifiedSentence);
        clientSocket.close();
    }
}

这是服务器代码:

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String capitalizedSentence;
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while(true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
        }
    }
}

当我在两台不同的机器上运行它时,我唯一改变的是客户端程序使用服务器程序(我从 whatismyipaddress.com 获得)使用机器的 IP 地址创建其套接字。非常感谢您的帮助。

更新:我确实在校园里,似乎它可能不允许我使用那个随机端口。有关找出我可以使用的端口和/或很可能允许的端口的任何建议?

【问题讨论】:

  • 你可以通过这个IP地址连接到服务器吗? (使用 ping/telnet/traceroute/等)
  • 在尝试调试程序之前,请先尝试确保您可以 ping 另一台计算机。这样你就知道网络不是罪魁祸首。

标签: java sockets


【解决方案1】:

这可能是防火墙问题。确保在服务器端转发要连接的端口。 localhost 直接映射到一个 ip 并在您的网络堆栈中移动。您正在更改代码中的一些文本,但程序的工作方式基本相同。

【讨论】:

  • 尝试使用客户端计算机上的 telnet 测试与服务器的连接。如果您收到“连接被拒绝”或超时,那就是防火​​墙问题
  • 如果你在学校,你几乎肯定有一个路由器。 Ping 无济于事。它验证机器是否可访问,但如果您的端口已打开,则无法访问。您可以尝试使用浏览器连接到远程机器,您应该会得到类似“GET / HTTP 1.1”的信息。或者你可以试试 curl 之类的东西。
【解决方案2】:

IP 路由有一个基本概念:如果您希望您的机器可以通过 Internet 访问,则您必须有一个唯一的 IP 地址。这称为“公共 IP 地址”。 “www.whatismyipaddress.com”会给你这个。如果您的服务器位于某个默认网关之后,IP 数据包将通过该路由器到达您。外界无法通过您的私有 IP 地址联系您。您应该注意,客户端和服务器的私有 IP 地址可能相同,只要它们对应的默认网关具有不同的地址(这就是 IPv4 仍然有效的原因) 我猜您正在尝试从您的客户端的私有地址 ping 到服务器的公共 IP 地址(由 whatismyipaddress.com 提供)。这是不可行的。为了实现这一点,需要从私有地址到公共地址的映射,简称为网络地址转换或 NAT。这是在防火墙或路由器中配置的。 您可以创建自己的专用网络(例如通过 wifi)。在这种情况下,由于您的客户端和服务器将位于同一逻辑网络上,因此不需要将私有地址转换为公共地址,因此您只能使用私有 IP 地址进行通信。

【讨论】:

    【解决方案3】:

    如果您从外部网站 (http://whatismyipaddress.com/) 获得 IP 地址,则您拥有外部 IP 地址。如果您的服务器在同一个本地网络上,您可能需要一个内部 IP 地址。 Local IP addresses 看起来像 10.X.X.X、172.X.X.X 或 192.168.X.X。

    尝试this page 上的建议,找出您的机器认为它的 IP 地址是什么。

    【讨论】:

    • (请注意,并非所有 172.X.X.X 地址都是本地的。)
    • 我也是从 ipconfig 得到的,它是一样的。
    【解决方案4】:

    与其使用来自 whatismyipaddress.com 的 IP 地址,不如直接从机器上获取 IP 地址并将其插入会怎样? whatismyipaddress.com 将为您提供路由器的地址(我假设您在家庭网络上)。我认为端口转发不会起作用,因为您的请求将来自网络内部,而不是外部。

    【讨论】:

    • 我也做了 ipconfig,它给出了与 whatismyipaddress.com 相同的地址
    • 你是在校园网还是什么的?他们可能将其交换机/路由器配置为阻止某些端口,即使是来自网络内的端口。如果您在这不起作用时可以 ping 另一台计算机,则该端口可能被阻止。
    • 是的,我在校园里,我猜我应该用端口 80 试试看我有没有运气?
    【解决方案5】:

    Outstream 未关闭...关闭流,以便响应返回到测试客户端。 希望这会有所帮助。

    【讨论】:

      【解决方案6】:

      您可以从您连接的路由器的 DHCP 列表中获取该计算机运行服务器程序的 ip。

      【讨论】:

      • 你能改写这个答案来澄清它吗?我觉得你的意思不是很清楚。
      • 我的意思不是写Socket clientSocket = new Socket("localhost", 6789); localhost 意味着同一台计算机,因此他必须找到运行服务器的计算机的IP。如果在这种情况下使用路由器:那么他可以打开路由器网页以查找 DHCP 列表,该列表将显示连接到路由器的设备以及每个设备的 IP。
      【解决方案7】:

      我尝试做客户端套接字程序

      服务器读取文件并将其打印到控制台并将其复制到输出文件

      服务器程序:

      package SocketProgramming.copy;
      
      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.net.ServerSocket;
      import java.net.Socket;
      
      public class ServerRecieveFile {
          public static void main(String[] args) throws IOException {
              // TODO Auto-enerated method stub
              int filesize = 1022386;
              int bytesRead;
              int currentTot;
              ServerSocket s = new ServerSocket(0);
              int port = s.getLocalPort();
              ServerSocket serverSocket = new ServerSocket(15123);
              while (true) {
                  Socket socket = serverSocket.accept();
                  byte[] bytearray = new byte[filesize];
                  InputStream is = socket.getInputStream();
                  File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
                  FileOutputStream fos = new FileOutputStream(copyFileName);
                  BufferedOutputStream bos = new BufferedOutputStream(fos);
                  bytesRead = is.read(bytearray, 0, bytearray.length);
                  currentTot = bytesRead;
                  do {
                      bytesRead = is.read(bytearray, currentTot,
                              (bytearray.length - currentTot));
                      if (bytesRead >= 0)
                          currentTot += bytesRead;
                  } while (bytesRead > -1);
                  bos.write(bytearray, 0, currentTot);
                  bos.flush();
                  bos.close();
                  socket.close();
              }
          }
      }
      

      客户端程序:

      package SocketProgramming.copy;
      
      import java.io.BufferedInputStream;
      import java.io.BufferedReader;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileReader;
      import java.io.IOException;
      import java.io.OutputStream;
      import java.net.InetAddress;
      import java.net.ServerSocket;
      import java.net.Socket;
      import java.net.UnknownHostException;
      
      public class ClientSendFile {
          public static void main(String[] args) throws UnknownHostException,
                  IOException {
              // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
              final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
              ServerSocket s = new ServerSocket(0);
              int port = s.getLocalPort();
              Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
              System.out.println("Accepted connection : " + socket);
              File transferFile = new File(FILE_NAME);
              byte[] bytearray = new byte[(int) transferFile.length()];
              FileInputStream fin = new FileInputStream(transferFile);
              BufferedInputStream bin = new BufferedInputStream(fin);
              bin.read(bytearray, 0, bytearray.length);
              OutputStream os = socket.getOutputStream();
              System.out.println("Sending Files...");
      
              os.write(bytearray, 0, bytearray.length);
      
              BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
              String as = "", line = null;
              while ((line = r.readLine()) != null) {
                  as += line + "\n";
                  // as += line;
      
              }
              System.out.print("Input File contains following data: " + as);
              os.flush();
              fin.close();
              bin.close();
              os.close();
              socket.close();
      
              System.out.println("File transfer complete");
          }
      }
      

      【讨论】:

      • 请不要多次发布您的答案!您可以按答案下方的编辑按钮来改进它。
      【解决方案8】:

      这是客户端代码

      首先运行服务器程序,然后在另一个 cmd 上运行客户端程序

      import java.io.*;
      import java.net.*;
      
      public class frmclient 
      {
       public static void main(String args[])throws Exception
       {
      
         try
              {
                DataInputStream d=new DataInputStream(System.in);
                System.out.print("\n1.fact\n2.Sum of digit\nEnter ur choice:");
      
                 int ch=Integer.parseInt(d.readLine());
                 System.out.print("\nEnter number:");
                 int num=Integer.parseInt(d.readLine());
      
                 Socket s=new Socket("localhost",1024);
      
                 PrintStream ps=new PrintStream(s.getOutputStream());
                 ps.println(ch+"");
                 ps.println(num+"");
      
                DataInputStream dis=new DataInputStream(s.getInputStream());
                 String response=dis.readLine();
                       System.out.print("Answer:"+response);
      
      
                      s.close();
              }
              catch(Exception ex)
              {
      
              }
       }
      
      
      }
      

      这是服务器端代码

      import java.io.*;
      import java.net.*;
      public class frmserver {
      
        public static void main(String args[])throws Exception
        {
      
      try
          {
      
          ServerSocket ss=new ServerSocket(1024);
             System.out.print("\nWaiting for client.....");
             Socket s=ss.accept();
             System.out.print("\nConnected");
      
             DataInputStream d=new DataInputStream(s.getInputStream());
      
              int ch=Integer.parseInt(d.readLine());
             int num=Integer.parseInt(d.readLine());
               int result=0;
      
              PrintStream ps=new PrintStream(s.getOutputStream());
              switch(ch)
              {
                case 1:result=fact(num);
                       ps.println(result);
                        break;
                case 2:result=sum(num);
                       ps.println(result);
                        break;
              }
      
                ss.close();
                s.close();
          }
      catch(Exception ex)
      {
      
      }
        }
      
        public static int fact(int n)
        {
        int ans=1;
          for(int i=n;i>0;i--)
          {
            ans=ans*i;
          }
          return ans;
        }
        public static int sum(int n)
        {
         String str=n+"";
         int ans=0;
          for(int i=0;i<str.length();i++)
          {
            int tmp=Integer.parseInt(str.charAt(i)+"");
            ans=ans+tmp;
          }
          return ans;
        }
      }
      

      【讨论】:

        【解决方案9】:
        import java.io.*;
        import java.net.*;
        class serversvi1
        {
          public static void main(String svi[]) throws IOException
          {
            try
            {
              ServerSocket servsock=new ServerSocket(5510);
              DataInputStream dis=new DataInputStream(System.in);
        
              System.out.println("enter the file name");
        
              String fil=dis.readLine();
              System.out.println(fil+" :is file transfer");
        
              File myfile=new File(fil);
              while(true)
              {
                Socket sock=servsock.accept();
                byte[] mybytearray=new byte[(int)myfile.length()];
        
                BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
        
                bis.read(mybytearray,0,mybytearray.length);
        
                OutputStream os=sock.getOutputStream();
                os.write(mybytearray,0,mybytearray.length);
                os.flush();
        
                sock.close();
              }
            }
            catch(Exception saranvi)
            {
              System.out.print(saranvi);
            }
          }
        }
        
        
        import java.io.*;
        import java.net.*;
        
        class clientsvi1
        {
          public static void main(String svi[])throws IOException
          {
            try
            {
              Socket sock=new Socket("localhost",5510);
              byte[] bytearray=new byte[1024];
        
              InputStream is=sock.getInputStream();
              DataInputStream dis=new DataInputStream(System.in);
              System.out.println("enter the file name");
        
              String fil=dis.readLine();
              FileOutputStream fos=new FileOutputStream(fil);
              BufferedOutputStream bos=new  BufferedOutputStream(fos);
              int bytesread=is.read(bytearray,0,bytearray.length);
              bos.write(bytearray,0,bytesread);
              System.out.println("out.txt file is received");
              bos.close();
              sock.close();
            }
            catch(Exception SVI)
            {
              System.out.print(SVI);
            }
          }
        }
        

        【讨论】:

        • 你能解释一下这段代码吗?它不会帮助任何想要了解正在发生的事情或 OP 为何会出现连接问题的人。
        • 请添加一些解释。您的回答目前被标记为“低质量”,最终可能会被删除。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        • 2015-12-25
        • 2018-01-30
        • 1970-01-01
        • 2013-07-03
        相关资源
        最近更新 更多