In this post we will see how to do interaction with TCP server data using socket in simple steps.
Step 1 : Connect with TCP server .
To connect with TCP server we need IP address and port number .
Step 2 : After connection we can send data to server.
Step 3 : When we send data to server we get response using following method.
Step 4 : To send commands to server we can use following method.
Step 5 : Close the socket connection after use.
I will edit in depth details for socket connection over TCP stream soon.
Happy coding !
Step 1 : Connect with TCP server .
To connect with TCP server we need IP address and port number .
private void startConnection() throws UnknownHostException, IOException {
Socket client = new Socket("Your IP address", "TCP_SERVER_PORT");
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
}
Step 2 : After connection we can send data to server.
private void sendDataOverServer() throws IOException {
String outMsg = "TCP connecting to " + TCP_SERVER_PORT+ System.getProperty("line.separator");
output.write(outMsg);
output.flush();
Log.v("TcpClient", "sent: " + outMsg);
}
Step 3 : When we send data to server we get response using following method.
private String receiveDataFromServer() throws IOException {
String inmsg = input.readLine() + System.getProperty("line.separator");
Log.i(getTag(), "received: " + inmsg);
return inmsg;
}
Step 4 : To send commands to server we can use following method.
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client
.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
out.println(etCommand.getText().toString());
'Step 5 : Close the socket connection after use.
private void closeConnection() throws IOException {
if(client != null)
client.close();
}
I will edit in depth details for socket connection over TCP stream soon.
Happy coding !
No comments:
Post a Comment