TelnetClient telnet = new TelnetClient();
telnet.connect( "192.168.0.6", 23 );
PrintWriter out =
new PrintWriter(telnet.getOutputStream(), true);
DataInputStream in =
new DataInputStream(telnet.getInputStream());
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
byte buffer[] = new byte[1024];
int bytesRead;
while ((bytesRead=in.read(buffer,0,1024)) != -1) { // read from server
System.out.print(new String(buffer, 0, bytesRead, "UTF-8"));
userInput = stdIn.readLine();
if (userInput != null) {
out.println(userInput);
out.flush();
}
}
telnet.disconnect();
Hello I have a problem with this program during the connection to the server.
This program should allow me to start a telnet connection to a server and send to it some commands and return me the result of these but when I start the connection some times it return me only the HELLO of the server (Welcome to Microsoft Telnet Service) and not the entire message including LOGIN:
When I send commands the response of these is delayed.
For example i write "DIR" and the response is written only when I press enter two times...
Where I wrong? Please help me.
When trying to connect to network services using such protocol (Telnet, FTP ,SSH ..) which are session based protocol and require to keep your connection alive and be interactive with the service , it's recommended to use available Java API instead of reinventing the wheel (only if you are asked to do without a third party library), in your case you can use Apache Common Net wich provide a set of helpful features to connect to servers using many network protocols including Telnet .
Related
I am creating a program where an android device requests a file from a Web Server(running python).The server can receive over sockets with no problem the path of the requested file but i dont know how i can make my android device to wait for a responce.
Here is the android code(as a client requesting a file from web server):
try {
Socket socket = null;
socket = new Socket("192.168.1.9", 4000);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
String str = getURL();
output.writeBytes(str);
output.close();
input.close();
socket.close();
{
}
} catch (IOException e) {
}
Log.d("communicationService", "URL transferred with success");
And the python script running on Web Server(It can receive thefile path but i have problem sending the file)
import socket
import sys
HOST, PORT = '192.168.1.9', 4000
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind((HOST,PORT))
serverSocket.listen(10)
print 'Server is on and listening to %s ... ' % PORT
while True:
clientSocket, clientAddress = serverSocket.accept()
print 'A client was connected.....'
incomingURL = clientSocket.recv(1024)
print incomingURL
clientSocket.close()
Any advice and tip would be really helpful...
I imagine you should be able to get away with SimpleHTTPServer
If you need to get fancier with a full blown webservice, WSGI is very popular.
On the client side Requests library is by far the easiest way that I've found to make http requests in python. (just had to plug that one because it's that good)
Well i managed to transfer the files in the end(For those that are interested in apps of this kind).What i did was to create another socket and sent a stream back to client.
file = open("path_of_file", "rb")
s = socket.socket()
s = connect((addr,port))
l = file.read(1024)
while (l):
s.send(l)
l.f.read(1024)
file.close()
s.close()
I'm developing an Android client app which talks to server via a plain TCP Socket, let's assume that the server ip 192.168.1.2 and the androdi device ip is 192.168.1.3.
I open the socket, i check if socket is connected (i get true as result) and after that i write a presentation message.
Here is my code
// scoket setup
Sockets = new Socket(addressToConnect, 2015);
s.setSoTimeout(2500);
setTcpNoDelay(true);
// if i'm connected
if (s.isConnected()) {
// wrapping streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// sending data
String presentationMessage = "Presentation message content--- TERM";
dos.write(presentationMessage.getBytes("UTF-8");
dos.flush();
// buffers
byte[] readBuffer = new byte[4096];
StringBuffer responseBuffer = new StringBuffer();
// read data until command terminator string is found
boolean readResponse = true;
while (readResponse) {
int dataBufferLength = dis.read(readBuffer);
String chunk = new String(readBuffer, 0, dataBufferLength, "UTF-8"));
responseBuffer.append(chunk);
readResponse = ! chunk.endWith("--- TERM");
}
// Process data here
} else {
// Notify missing connection here
}
// here i close the socket
When i execute this code the execution seems working like a charme until the first read which timesout.
Sniffing the used WIFI network with a third machine i can't see the connection establishment and the written stream even if the code doesn't throw any exception before the read timeout.
I granted the android.permission.INTERNET in manifest.
Are there some other permissions to grant? or what i'm doing wrong?
Executing the same code in a standard Java SE environment everything goes fine.
I'm testing the code on a Nexus 5, Nexus 9 and Samsung S3 and S4 and the project is compatible with API 14+
Edit: Fixed typo in code example
You are reading from dos and writing to dis. You should reverse that.
I am writing a proxy server in Java.
Initially, I do (simplified)
server = new ServerSocket(5568);
incoming = server.accept();
input = incoming.getInputStream();
...
outgoing = new Socket(host, 80);
output = outgoing.getOutputStream();
output.write(inputbuffer, 0, i);
where inputbuffer is some collection of bytes received so far (I read the incoming data up until the part where I know the host header, and then open a connection to the server and send what I have so far). So server is my welcome socket, input is the data coming to my proxy from the client, and output is the data to the serve from my proxy.
Next, I want the output from the server to be written to the client in parallel with the client still possibly writing stuff to the server. So I create a separate thread to read from the client:
final InputStream finalInput = input;
final OutputStream finalOutput = output;
Thread sendingStuff = new Thread(){
public void run(){
int c;
while ((c = finalInput.read()) != -1){
finalOutput.write((byte)c);
finalOutput.flush();
}
finalInput.close();
finalOutput.close();
}
}
sendingStuff.start();
Finally, I have a different section in the main thread to read from the server and write that to the client.
InputStream reverseInput = outgoing.getInputStream();
OutputStream reverseOutput = incoming.getOutputStream();
int c;
while ((c = reverseInput.read()) != -1){
reverseOutput.write((byte)c);
reverseOutput.flush();
}
reverseInput.close();
reverseOutput.close();
What happens is I get input, and send output, but the browser spins forever and the line in the thread that's reading from the client never gets a -1 signal.
A lot of the time I get errors that say things like "invalid header name" or "your browser sent a request that the server could not understand" and I think it has to do with this problem I'm having. One time I even got an IOException: Socket Closed on the line that reads from the client.
So why isn't the client sending an EOF? And is this the right way to go about doing this?
"I think it's because my HTTP request has Connection: keep-alive. How do I handle this?"
I think maybe you can just open your socket once for one connection.
Try to have flag like isNewConnection. set it to true at first and after the connection is initiated, set it to false.
I have a Socket listening on some x port.
I can send the data to the socket from my client app but unable to get any response from the server socket.
BufferedReader bis = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = bis.readLine()) != null)
{
instr.append(inputLine);
}
This code part reads data from server.
But I can't read anything from server until unless the Socket on the server is closed.
Server code is not under my control to edit something on it.
How can I overcome this from client code.
Thanks
Looks like the server may not be sending newline characters (which is what the readLine() is looking for). Try something that does not rely on that. Here's an example that uses the buffer approach:
Socket clientSocket = new Socket("www.google.com", 80);
InputStream is = clientSocket.getInputStream();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
pw.println("GET / HTTP/1.0");
pw.println();
pw.flush();
byte[] buffer = new byte[1024];
int read;
while((read = is.read(buffer)) != -1) {
String output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
};
clientSocket.close();
To communicate between a client and a server, a protocol needs to be well defined.
The client code blocks until a line is received from the server, or the socket is closed. You said that you only receive something once the socket is closed. So it probably means that the server doesn't send lines of text ended by an EOL character. The readLine() method thus blocks until such a character is found in the stream, or the socket is closed. Don't use readLine() if the server doesn't send lines. Use the method appropriate for the defined protocol (which we don't know).
For me this code is strange:
bis.readLine()
As I remember, this will try to read into a buffer until he founds a '\n'. But what if is never sent?
My ugly version breaks any design pattern and other recommendations, but always works:
int bytesExpected = clientSocket.available(); //it is waiting here
int[] buffer = new int[bytesExpected];
int readCount = clientSocket.read(buffer);
You should add the verifications for error and interruptions handling too.
With webservices results this is what worked for me ( 2-10MB was the max result, what I have sent)
Here is my implementation
clientSocket = new Socket(config.serverAddress, config.portNumber);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (clientSocket.isConnected()) {
data = in.readLine();
if (data != null) {
logger.debug("data: {}", data);
}
}
I'm trying to create a simple library (hope to share it with the world) that will allow to send and receive commands to remote equipment via telnet.
I'm trying to keep the code as simple as possible and it's already working, but I can't seem to understand how the input stream is working;
I'm reading each line separately and normally input should stop at input "Username:" after which I should type in my username.
What actually happens is that after I detect that I've received this line and send a response it is already too late (new input has already been received).
Any idea how a telnet session actually works and how the last command (after which the remote equipment waits) is received?
import java.util.*;
import java.io.*;
import java.net.*;
public class telnet {
public static void main(String[] args){
try{
//socket and buffer allocation
Scanner scan = new Scanner (System.in);
Socket socket = null;
PrintWriter out;
BufferedReader in;
String input; // temp input
String input1="";
String buff = ""; // holds all the input
//socket and IO initialization
socket = new Socket("10.10.10.2", 23);
out = new PrintWriter(socket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int i=0;
int j=0;
while(true){
input = in.readLine(); //printout given line
System.out.println("line "+i+":\n"+input);
if (input.contains("Username")){ //if reading 'username' send response
System.out.println("!got Username");
out.println("user");
continue;
}
if (input1.contentEquals(input)){ //if input is the same wait once then send ENTER
if (j==0){
System.out.println("!read same line. wait for new");
i++; j++;
continue;
}
else{
System.out.println("!no new line. sending ENTER");
out.println("\r");
i++;j=0;
}
} else {j=0;}
input1=""; //copy input to temp string to check if same line or new
input1.concat(input);
i++;
if (i==20) break;
}
//CLOSE
out.close();
in.close();
socket.close();
} catch(IOException e){}
}
}
A telnet server and telnet client don't just send plain text back and forth. There is a telnet protocol, and both the client and server can send commands to each other. The telnet server that you are connecting to may be trying to negotiate some setting change with your program, and your program may be interpreting the byte stream as lines of text.
The standard Unix telnet client program will suppress using the telnet protocol when it's not talking to an actual telnet server. Instead, it will fall back to sending text line-by-line and printing anything received from the server. This allows the program to be used to communicate with SMTP servers, HTTP servers, and the like. The telnet server doesn't necessarily have this fallback behavior; it may always assume that the client implements the protocol.