gpt4 book ai didi

java - TCP/IP 打开连接

转载 作者:行者123 更新时间:2023-12-02 00:28:52 24 4
gpt4 key购买 nike

目前我正在使用以下代码与服务器交互

  public String connectToserverforincomingmsgs(String phonurl, String phno)
throws IOException {
URL url = new URL(phonurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);

// Allow Outputs
con.setDoOutput(true);
con.connect();
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
con.getOutputStream(), "UTF-8"));
// give server your all parameters and values (replace param1 with you
// param1 name and value with your one's)
writer.write("sender_no=" + phno);

writer.flush();

String responseString = "";

BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;

while ((line = reader.readLine()) != null) {
responseString = responseString.concat(line);
}
con.disconnect();
return responseString;

}

我怎样才能建立tcp连接。现在我不知道。我对 android 和 java 都很陌生,所以任何有关 tcp 连接的示例代码将不胜感激

最佳答案

要创建 TCP 连接,您需要使用套接字:

Socket socket = new Socket(host_name_or_ip_address, port_no);

要发送数据,请使用socket.getOutputStream()

要接收数据,请使用socket.getInputStream()

关于java - TCP/IP 打开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com