Reputation: 37
I have taken the Socket Ip and port which is entered manually, and now i want to set timeout for the socket connection. As well how to send data to the client in the below code.
public void run() {
try {
socket = new Socket(eHostIp.getText().toString(), Integer.parseInt( eHostPort.getText().toString() ) );
socket.connect( );
//PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//out.println("");
eReceiveData.setText( "Server Connected" );
//eReceiveData.setText( socket.getInputStream().read() );
BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ), 1024 );
eReceiveData.setText( "Server Connected... XXXXXXX" );
String line;
while ((line = in.readLine()) != null) {
Log.d("read line",line);
eReceiveData.setText( line );
socket.close();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} );
thread.start();
Upvotes: 1
Views: 683
Reputation: 4067
Use Socket.connect(SocketAddress endpoint, int timeout) method to specify timeout.
In order to write to a socket get output stream from it (via socket.getOutputStream()) and write to that output stream.
Note: don't close socket in your while loop! You can't write to a socket after you've closed it.
Upvotes: 1