2010-01-29 167 views
18

我正在写我的第一个Java客户端/服务器程序,它只是建立与服务器的连接发送一个句子,服务器将句子全部大写。这实际上是书中的一个例子,当我在同一台计算机上运行客户端和服务器并使用localhost作为服务器地址时,它运行良好。但是当我将客户端程序放在另一台计算机上时,它会超时并且永远不会与服务器建立连接。我不确定这是为什么,它是制造你的第一个客户端/服务器程序,而实际上不能在两台不同的机器上使用它。下面是客户端代码:简单的Java客户端/服务器程序

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

,当我在两台不同的机器上运行它,我改变的唯一的事情是客户端程序使得其与IP地址插座与服务器程序(我从whatismyipaddress.com得到)的机器。非常感谢您的帮助。

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

+1

并且你可以通过这个IP地址连接到服务器除此以外? (使用ping/telnet/traceroute /等) – McDowell 2010-01-29 21:05:57

+0

在尝试调试程序之前,可能尝试并确保可以先ping其他计算机。这样你就知道网络不是责任。 – 2010-01-29 21:07:16

+0

我试过ping,它工作。 – Anton 2010-01-29 21:15:47

回答

8

这可能是一个防火墙问题。确保你在服务器端转发你想连接的端口。本地主机直接映射到一个IP地址,也移动通过您的网络堆栈。您正在更改代码中的某些文本,但程序的工作方式基本相同。

+0

尝试从客户端计算机使用telnet 测试与服务器的连接。如果你得到“连接被拒绝”或超时,那是一个防火墙问题 – 2010-01-29 21:05:51

+1

如果你在学校,你几乎肯定有一台路由器。平安不会有太大帮助;它会验证机器是否可到达,但如果您的端口已打开,则不会。你可以尝试使用你的浏览器连接到远程机器,你应该回到“GET/HTTP 1.1”之类的东西。或者你可以尝试像卷曲的东西。 – TMN 2010-01-29 21:23:24

1

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

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

+0

(请注意,并非所有的172.X.X.X地址都是本地的。) – 2010-01-29 21:03:30

+0

我从ipconfig得到它,它也是一样的。 – Anton 2010-01-29 21:05:21

1

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

+0

我做了ipconfig以及它给了与whatismyipaddress.com相同的地址 – Anton 2010-01-29 21:04:35

+0

你是在校园网络还是什么?他们可能会将其交换机/路由器配置为阻止某些端口,即使在网络内也是如此。如果您在另一台计算机无法工作时可以ping通另一台计算机,则该端口可能会被阻塞。 – Neal 2010-01-29 21:18:31

+0

是的,我在校园里我猜我应该尝试80端口,看看我有没有运气? – Anton 2010-01-29 21:20:48

3

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

0

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

0

你可以从你连接的路由器的DHCP列表中获得该计算机的IP地址。

+0

你能改述这个答案来澄清它吗?我不认为你的意思是非常清楚的。 – skrrgwasme 2014-09-06 01:30:33

+0

我的意思不是写'Socket clientSocket = new Socket(“localhost”,6789);'localhost意味着同一台计算机,所以他必须找到计算机运行服务器的IP地址。如果在这种情况下使用路由器:那么他可以打开路由器网页来查找将显示设备连接到路由器的DHCP列表,并为每个设备分配一个IP。 – user3417593 2014-09-07 08:49:33

0

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

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

服务器程序:

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

请不要多次发布您的答案!您可以按下答案下方的编辑按钮以改进它。 – honk 2014-10-30 19:34:02

+0

也为你的代码添加一些解释。 – 2014-10-30 23:20:19

0

This is cl ient代码

第一次运行的服务器程序,然后在另一个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; 
    } 
} 
-1
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); 
    } 
    } 
} 
+2

你能解释一下这段代码吗?它不会帮助任何想了解正在发生的事情的人,或者OP为什么会遇到连接问题。 – 2016-03-11 03:14:27

+0

请添加一些解释。您的答案目前被标记为“低质量”,并可能最终被删除。 – 2016-03-11 10:33:21