我正在创建一个简单的客户端/服务器应用程序 并能够将多个客户端连接到单个服务器。 我提到了这个链接client/server simple app demo
我的问题是,现在,我想从服务器向客户端返回一些响应 基于其客户端/ IP地址。
例如。如果192.123.1.1连接响应应该是xml
如果192.123.1.2连接响应应该是json。
有可能做到吗?任何帮助将不胜感激
这是我的简单服务器代码:
public class ChatServer implements Runnable
{
private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start()
public void stop()
public static void main(String args[])
答案 0 :(得分:2)
我认为客户端应该询问他们想要的数据类型而不是ip检查。我不确定你为什么需要检查ip。但是将来如果你有更多的客户端,那么你每次都必须更改服务器代码。最好在客户端中定义格式,以便客户端可以请求特定类型的数据。
不太确定您的要求。
答案 1 :(得分:1)
有一个API调用Socket.getRemoteSocketAddress().toString()
来获取来电者IP
Socket clientSocket =server.accept();
System.out.println(" client ip address =" +clientSocket.getRemoteSocketAddress().toString());
- 一旦获得clientSocket,请使用下面的示例回写
Socket clientSocket =server.accept();
String returMessage ="Hello from Server ";
if (clientSocket.getRemoteSocketAddress().toString().equals("192.168.1.3")){
returMessage=returMessage +" welcome browser";
}
else if(clientSocket.getRemoteSocketAddress().toString().equals("192.168.1.4")){
returMessage=returMessage +" welcome tablet";
}
OutputStream os = clientSocket .getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returMessage);
System.out.println("Message sent to the client is "+returMessage);
bw.flush();
- 从客户端阅读
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = br.readLine();
System.out.println("Message received from client is "+data);
if("send_players".equals(data)){ // reading data you would need to finetune
//write playerlist
}