简体   繁体   English

tcp/ip 打开连接

[英]tcp/ip open connection

currently i am using the following code to interact with server目前我正在使用以下代码与服务器交互

  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;

}

how could i make tcp connection .right now i don't have any idea .我怎么能建立 tcp 连接。现在我不知道。 i am new to android and java aswell so any sample code about the tcp connection would be appreciated我也是 android 和 java 的新手,所以任何关于 tcp 连接的示例代码都将不胜感激

To create a TCP Connection you need to Use Socket:要创建 TCP 连接,您需要使用 Socket:

Socket socket = new Socket(host_name_or_ip_address, port_no);

To Send Data use socket.getOutputStream()发送数据使用socket.getOutputStream()

To Receive Data use socket.getInputStream()接收数据使用socket.getInputStream()

Just replace HttpURLConnection with Socket.只需将 HttpURLConnection 替换为 Socket。 It works pretty much the same它的工作原理几乎相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM