Showing posts with label Socket. Show all posts
Showing posts with label Socket. Show all posts

How to Create a New Streaming Socket Connected to Target Host

public Socket (String dstName, int dstPort) was added in API level 1
Creates a new streaming socket connected to the target host specified by the parameters dstName and dstPort. The socket is bound to any available port on the local host.
This implementation tries each IP address for the given host name (in RFC 3484 order) until it either connects successfully or it exhausts the set.
Parameters:
dstName - the target host name or IP address to connect to.
dstPort - the port on the target host to connect to.
Throws:
UnknownHostException - if the host name could not be resolved into an IP address.
IOException - if an error occurs while creating the socket.

1. Declare a Socket named mySocket.

2. In the MainActivity. add the below imports to the import section. 

import java.net.UnknownHostException;
import java.io.IOException;
4. In the onCreate, add the below code to create a new streaming socket connected to a target host. For example, you can connect to your IP address (my example: 192.168.1.1) with a port address of 8888. The e.printStackTrace will be sent to your LogCat. For direct errors, you may add a toast

try {
mySocket = new Socket("192.168.1.1", 8888);
} catch (UnknownHostException e) {
//Toast.makeText(this, "Socket Error: UnknownHostException", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
//Toast.makeText(this, "Socket: IOExcpetion", Toast.LENGTH_LONG).show();

e.printStackTrace();
}

5. Compile and run!

Resources:
http://developer.android.com/reference/java/net/Socket.html
http://android-er.blogspot.com/2011/01/simple-communication-using.html

How to Initialize a Socket object

Socket was added in API Level 1

1. Declare a Socket named mySocket.

2. In the MainActivity.java file, in the onCreate method, add the line below. This will initialize the mySocket object to null.

mySocket = null;

3. Compile and run!

Next Recommended Article: How to Create a New Streaming Socket Connected to Target Host

Resources:
http://developer.android.com/reference/java/net/Socket.html
http://android-er.blogspot.com/2011/01/simple-communication-using.html

How to Declare a Socket

Socket was added in API Level 1
Provides a client-side TCP socket.

1. In the MainActivity.java file, add the below import to the imports section.

import java.net.Socket;

2. In the onCreate method, add the below line to declare a new Socket named mySocket.

Socket mySocket;