我知道如何使用带有 JSON 的 PHP 脚本与服务器通信,但如果服务器是用 Java 编写的,我将如何使用我的 Java 程序与服务器通信。
它会相同还是有一些更简单的方法可以排除 JSON?
我习惯这样做的方式是使用发布请求,然后在 JSON 中编码/解码
它不是网络服务器
我知道如何使用带有 JSON 的 PHP 脚本与服务器通信,但如果服务器是用 Java 编写的,我将如何使用我的 Java 程序与服务器通信。
它会相同还是有一些更简单的方法可以排除 JSON?
我习惯这样做的方式是使用发布请求,然后在 JSON 中编码/解码
它不是网络服务器
您可以使用如下所示的服务器套接字编程作为客户端您可以像这样编写代码
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])
{
try
{
Socket server;
String str="";
DataInputStream d=new DataInputStream(System.in);
PrintStream toserver;
BufferedReader fromserver;
server=new Socket("117.198.219.36",1096); //your ip to connect and port no through which you will connect to server
InputStreamReader isr=new InputStreamReader(server.getInputStream());
fromserver= new BufferedReader(isr);
toserver=new PrintStream(server.getOutputStream());
while(true)
{
str=":"+d.readLine();
toserver.println(str);
str=fromserver.readLine();
System.out.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
这是发送请求的客户端程序。
现在服务器端程序在下面,您将提供相同的端口号来连接到客户端。
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[])
{
ServerSocket sc;
Socket client;
DataInputStream d;
PrintStream toClient;
BufferedReader fromClient;
String str="";
try
{
d=new DataInputStream(System.in);
sc=new ServerSocket(1096); //the same port no that we had given at client side
System.out.println("ServerStarted");
client=sc.accept();
InputStreamReader isr=new InputStreamReader(client.getInputStream());
fromClient=new BufferedReader(isr);
toClient=new PrintStream(client.getOutputStream());
while(true)
{
str=fromClient.readLine();
System.out.println(str);
str=":"+d.readLine();
toClient.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
尝试使用它们,您将能够通过此连接。我希望这会对您有所帮助。
最有效的方法是使用Sockets。本教程很好地展示了客户端/服务器示例。
您可以随心所欲地进行交流,但是 java 开发人员更喜欢 rpc ( http://en.wikipedia.org/wiki/Remote_procedure_call ) 这是某些框架实现的最简单的方法,但是如果您需要完全控制您的消息,您可以做到认为 json 甚至直接通过套接字(但我不建议这样做)。