如果我从应用程序服务器上运行的应用程序建立套接字连接,返回的数据在哪里?是否有必要在具有指定端口的应用程序中创建接收服务器套接字,或者是否在服务器用于连接到应用程序的端口上接收,我只需要编写将提取该数据的内容?
答案 0 :(得分:0)
以下是从套接字读取的代码。您正在与服务器中的端口8080建立套接字连接。您不必担心操作系统 - >服务器端口。
public static void readSocket() throws IOException {
try (Socket s = new Socket(InetAddress.getByName(new URL("Some Address").getHost()), 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
}
答案 1 :(得分:0)
套接字是网络服务器和客户端程序之间双向通信链路的一个端点。
返回的数据正在发送到您的客户端Socket对象,我们称之为clientSocket
。您需要致电clientSocket.getInputStream()
进行解码。
不,您不需要在应用程序中创建接收服务器套接字。您的客户端程序在给定主机和端口上建立与服务器的连接。 clientSocket
可以将数据发送到服务器并从服务器接收数据。
例如客户端代码:
private PrintWriter out = null;
private BufferedReader in = null;
public void listenSocket(){
//Create socket connection
try{
clientSocket = new Socket(HOST, PORT);
// use out object to send data to server applicaiton
out = new PrintWriter(clientSocket.getOutputStream(),
true);
// uses in object to receive data from server application
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + HOST);
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
}
}