简单的 Java 客户端/服务器程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2165006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:18:19  来源:igfitidea点击:

Simple Java Client/Server Program

javasockets

提问by Anton

I'm writing my first java client/server program which just establishes a connection with the server sends it a sentence and the server sends the sentence back all capitalized. This is actually an example straight out of the book, and it works well and fine when I'm running the client and server on the same machine and using localhost for the server address. But when I put the client program on a different computer, it times out and never makes a connection with the server. I'm not sure why this is and its kind of lame making a your first client/server program and not actually be able to use it on two different machines. Here is the client code:

我正在编写我的第一个 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();
    }
}

Here is the server code:

这是服务器代码:

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);
        }
    }
}

The only thing I change when I run it on two different machines is the client program makes its socket with the IP address of the machine with the server program (which I got from whatismyipaddress.com). Thanks a lot for any help.

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

Update: I am indeed on a campus and it seems that its probably not allowing me to use that random port. Any suggestions on finding out what port I can use and or a port that is more than likely allowed?

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

采纳答案by Chris H

It's probably a firewall issue. Make sure you port forward the port you want to connect to on the server side. localhost maps directly to an ip and also moves through your network stack. You're changing some text in your code but the way your program is working is fundamentally the same.

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

回答by Michael Brewer-Davis

If you got your IP address from an external web site (http://whatismyipaddress.com/), you have your external IP address. If your server is on the same local network, you may need an internal IP address instead. Local IP addresseslook like 10.X.X.X, 172.X.X.X, or 192.168.X.X.

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

Try the suggestions on this pageto find what your machine thinks its IP address is.

尝试此页面上的建议以查找您的机器认为其 IP 地址是什么。

回答by Neal

Instead of using the IP address from whatismyipaddress.com, what if you just get the IP address directly from the machine and plug that in? whatismyipaddress.com will give you the address of your router (I'm assuming you're on a home network). I don't think port forwarding will work since your request will come from within the network, not outside.

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

回答by Vinit Shandilya

There is a fundamental concept of IP routing: You must have a unique IP address if you want your machine to be reachable via the Internet. This is called a "Public IP Address". "www.whatismyipaddress.com" will give you this. If your server is behind some default gateway, IP packets would reach you via that router. You can not be reached via your private IP address from the outside world. You should note that private IP addresses of client and server may be same as long as their corresponding default gateways have different addresses (that's why IPv4 is still in effect) I guess you're trying to ping from your private address of your client to the public IP address of the server (provided by whatismyipaddress.com). This is not feasible. In order to achieve this, a mapping from private to public address is required, a process called Network Address Translation or NAT in short. This is configured in Firewall or Router. You can create your own private network (say via wifi). In this case, since your client and server would be on the same logical network, no private to public address translation would be required and hence you can communicate using your private IP addresses only.

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

回答by Ravi raj

Outstream is not closed ... close the stream so that response goes back to test client. Hope this helps.

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

回答by user3417593

you can get ip of that computer runs server program from DHCP list in that router you connected to.

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

回答by Shree

My try to do client socket program

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

server reads file and print it to console and copies it to output file

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

Server Program:

服务器程序:

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();
        }
    }
}

Client program:

客户端程序:

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");
    }
}

回答by Prakash Ekhande

this is client code

这是客户端代码

first run the server program then on another cmd run client program

首先运行服务器程序,然后在另一个 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)
        {

        }
 }


}

this is sever side code

这是服务器端代码

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;
  }
}

回答by r.m.Vivek arni

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);
    }
  }
}