java TCP/IP 发送请求和得到响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13250552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TCP/IP Sending request and getting response
提问by Sandip Armal Patil
I am Working on TCP/IP
in Java. First, I read TCP/IP
and understand how it's working.
What i Need:-
Ok, Now i want to implement it in java. I am trying to Send some input in request to specific port/IP
from my IP. and need to get response.
I don't understand how to implement it.
Here is my Input:
我TCP/IP
在 Java 中工作。首先,我阅读TCP/IP
并理解它是如何工作的。
我需要什么:-
好的,现在我想在 Java 中实现它。我正在尝试port/IP
从我的 IP向特定请求发送一些输入。并且需要得到回应。
我不明白如何实现它。
这是我的输入:
Destination IP
Destination Port
Input(String or Anything)
Here is my code which i use for Client.
这是我用于客户端的代码。
try {
socket = new Socket("localhost", port);
}
catch(Exception e) {
System.out.println("Error connectiong to server:" + e);
return;
}
System.out.println("Connection accepted " +
socket.getInetAddress() + ":" +
socket.getPort());
/* Creating both Data Stream */
try
{
Sinput = new ObjectInputStream(socket.getInputStream());
Soutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException e) {
System.out.println("Exception creating new Input/output Streams: " + e);
return;
}
// now that I have my connection
String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
// send the string to the server
System.out.println("Client sending \"" + test + "\" to serveur");
try {
Soutput.writeObject(test);
Soutput.flush();
}
catch(IOException e) {
System.out.println("Error writting to the socket: " + e);
return;
}
// read back the answer from the server
String response;
try {
response = (String) Sinput.readObject();
System.out.println("Read back from server: " + response);
}
catch(Exception e) {
System.out.println("Problem reading back from server: " + e);
}
try{
Sinput.close();
Soutput.close();
}
Please give me some hint or reference.
请给我一些提示或参考。
回答by Vijay
Creating Scoketgo through this will help you. if you are implementing Sockets, you need to use ServerSocket class to create the ServerSocket . Then Socket class to request the create the connection between Client and Sever.
通过这个创建 Scoket会对你有所帮助。如果您正在实现 Sockets,则需要使用 ServerSocket 类来创建 ServerSocket 。然后 Socket 类请求在 Client 和 Sever 之间建立连接。