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

我正在编写我的第一个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地址创建其套接字。 非常感谢您的帮助。

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

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

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

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

尝试使用此页面上的建议来查找您的计算机认为其IP地址的内容。

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

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

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

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

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

服务器程序:

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

这是客户端代码

首先在另一个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 
 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); } } }