I have to send and receive with server some stream using java.
The protocol is telnet and if I use cmd in windows with this commands:"telnet 10.0.1.5 9100" and after "^AI202" I have a response.
The code java:
import java.io.*;
import java.net.*;
public static void main(String[] args) throws SocketException, IOException {
Socket s = new Socket();
PrintWriter s_out = null;
BufferedReader s_in = null;
String remoteip = "10.0.1.5";
int remoteport = 9100;
s.connect(new InetSocketAddress(remoteip , remoteport));
s_out = new PrintWriter( s.getOutputStream(), true);
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message = "^AI202";
try{
System.out.println(s_in.readLine());
}
catch(Error e){
System.out.println(e);
}
s_out.close();
s_in.close();
s.close();
}
The problem is the same: s_in call method readLine() and program cycle infinite.
I think System.out.println(s_in.readLine()); will try to read it over and over again, failing each time and causing infinite loop.
Try
String line ="";
while ((line = s_in.readLine()) != null) {
// Do what you want to do with line.
}
Java Socket BufferReader.readline get null
The problem is that the telnet protocol does not terminate commands with line breaks.
Change your read block to
try {
char [] cbuf = new char[7];
System.out.println(s_in.read(cbuf, 0, cbuf.length));
} catch(Error e){
System.out.println(e);
}
And you will get some input.
Related
I am building a server in Java, and the input feed is giving me trouble - its current setup cannot read more than one line, and it cannot read anything without "\n" at the end. Here is the current input loop:
BufferedReader input = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
if(input.ready()){
StringBuilder text = new StringBuilder();
String line;
while((line = input.readLine()) != null){
text.append(line);
System.out.println(line);
}
sentData = text.toString();
return true;
}
My current loop using a BufferedReader cannot read more than one line of incoming data, and if there is no newline character, a timeout exception is thrown (I programmed it to do that), and the data is not read at all. It is, of course, unacceptable to have a listener that can only see one line of data, and stalls when the sent data is not formatted properly.
So I am looking for a method that allows the program to read any number of lines, and for the program to stop reading when it has reached the end of the data stream (even without a new line).
Any help is appreciated.
You're throwing away every odd-numbered line. Remove the readLine() inside the loop.
You can read from the InputStream directly into the StringBuilder. readLine() of BufferedReader will wait for \r or \n character. This looks like stalling.
int ch;
StringBuilder text = new StringBuilder();
while((ch = serverConnection.getInputStream().read())!= -1) { // -1 will be read at EOS
text.append((char)ch);
}
sentData = text.toString();
return true;
Update
The following piece of code is to demonstrate the difference between usage of BufferedReader and InputStream to read bytes and what is available to the user during read operation. BufferedReader will always give you lines which are either terminated by line breaks or by EOS. Whereas InputStream will make the available bytes to the user.
In scenarios where it is NOT necessary to close the streams, and the bytes transferred has it's own way to mark start and end of packets/messages, you will be using InputStream to read bytes. If you try using BufferedReader for these applications, the last line of the message will be made available once the server receives the next packet/message, unless you send each line with a line-break.
public static void main(String[] args) throws Exception {
new Thread(new BufferedReaderServer()).start();
new Thread(new InputStreamServer()).start();
final String requestString = "Line#1\nLine#2";
System.out.println("\nSending to BufferedReaderServer");
Socket clientSocket1 = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 8003);
OutputStream outputStream1 = clientSocket1.getOutputStream();
outputStream1.write(requestString.getBytes());
Thread.sleep(6000);
outputStream1.close();
clientSocket1.close();
Thread.sleep(1000);
System.out.println("\nSending to InputStreamServer");
Socket clientSocket2 = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 8004);
OutputStream outputStream2 = clientSocket2.getOutputStream();
outputStream2.write(requestString.getBytes());
Thread.sleep(6000);
outputStream2.close();
clientSocket2.close();
}
static class BufferedReaderServer implements Runnable {
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8003);
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String s = null;
System.out.println("BufferedReaderServer read START");
while ((s = bufferedReader.readLine()) != null) {
System.out.println(s);
}
System.out.println("BufferedReaderServer read END");
socket.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
static class InputStreamServer implements Runnable {
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8004);
Socket socket = serverSocket.accept();
System.out.println("InputStreamServer read START");
int ch;
while ((ch = socket.getInputStream().read()) != -1) {
System.out.print((char) ch);
}
System.out.println("\nInputStreamServer read END");
socket.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The issue what is being faced here could be due to non-closing of client socket. Depends on the user's application
When I try to connect my client socket with a server I've to type a letter while it should connect automatically. The server is already made and works as it should without the client. When I type the letter it works but it should connect automaticallly.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String input=scan.next();
String text;
BufferedReader inFromUser;
Socket clientSocket;
inFromUser = new BufferedReader(new InputStreamReader(System.in));
clientSocket = new Socket("HH-PC", 4567);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while(true) {
input = scan.next();
if(input.equals("T")){
outToServer.writeBytes("T\r\n");
System.out.println(inFromServer.readLine());
}
else if(input.equals("S")){
outToServer.writeBytes("S\r\n");
System.out.println(inFromServer.readLine());
}
else if(input.equals("Z")){
outToServer.writeBytes("Z\r\n");
System.out.println(inFromServer.readLine());
}
else if(input.equals("D")){
System.out.println("Write a message");
text=inFromUser.readLine();
outToServer.writeBytes("D "+text + "\r\n");
System.out.println(inFromServer.readLine());
}
else if(input.equals("DW")){
outToServer.writeBytes("DW\r\n");
System.out.println(inFromServer.readLine());
}
else if(input.equals("Q")){
clientSocket.close();
System.out.println("The server is disconnected");
break;
}
}
}
}
The line
String input=scan.next();
is probably the problem. You are reading something at the beginning, but you are not using the value.
Try changing this line to
String input;
#Leonhard has identified the problem
In addition, you have two "streams" with buffering that are both reading from System.in. This is liable to lead to behavior that is hard to understand in edge cases. You should get rid of inFromUser and read that input using the existing scan object.
Here is my problem, have a server and a client class which communicate via 2 threads (MsgWriter and MsgReader)
To read the input and write it in a stream i use a scanner.
It works but the Scanner need an input twice to continue.
For example:
I write a Message
Your Message: a text.
So i want to send the message right after i hit "enter"
but i have to press enter another time to send the text.
I'm sorry, i'm very bad in explaining. however here is the Code of the MsgWriter Thread
public class MsgWriter extends Thread {
private Socket s;
private Buffer buffer = new Buffer();
public MsgWriter(Socket s) {
this.s = s;
}
public void run() {
String message = "";
BufferedReader br = null;
boolean end = false;
while(!end){
try{
synchronized (buffer) {
while (!buffer.isEmpty()) {
buffer.wait();
}
//buffer.put(s);
OutputStream out = s.getOutputStream();
PrintStream writer = new PrintStream(out);
Scanner input = new Scanner(System.in);
input.useDelimiter("\n");
if (input.nextLine().equals("")){
System.out.println("Your message: ");
message = input.next();
br = new BufferedReader(new StringReader(message));
if (input.hasNext("x")) {
br = new BufferedReader(new StringReader("Good Bye"));
end = true;
}
message = br.readLine();
writer.println(message);
System.out.println("-------------------------------");
}
buffer.notifyAll();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
}
And the Output
ServerIP: localhost/127.0.0.1
Port number: 56763
++ Connected to Server
Your message:
hi server
Received: hi client
Let me know if you need the Code of the MsgReader Thread as-well.
You have this line if (input.nextLine().equals("")) which looks for an empty string input and this is the reason your code waits for the second 'Enter' press. Any specific reason why you require this in the code?
I'm making a simple client-server application in Java. This is how I initialise the listening socket:
private void initSock() {
try {
sock = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: "+port+". Isn't the port already in use?");
System.exit(1);
}
}
That approach throws likely usefull error message when the port is used - however: Would it be possible to extend the info, like this:
Could not listen on port xx, it's being used by process blahblah with pid xxx.
Will Java (and Windows, and eventually other systems) allow me to fetch that info?
I can find this info using command line, but that's really not what I want at this moment.
I am not being able to fulfill your requirment, but below code can give you some more info:
public class NetStat
{
public static void main(String [] args) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter port number :");
String port =br.readLine();
StringBuffer output = new StringBuffer();
Process p = Runtime.getRuntime().exec("netstat -an");
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
if(line.contains(port))
{
output.append(line + "\n");
}
}
System.out.println(output.toString());
}
}
Input: 50773
Output: TCP 1xx.xxx.xxx.xxx:50773 xxx.xxx.xxx.xxx:8080 ESTABLISHED
package burak;
import java.io.*;
public class telcon {
public static void main(String[] args) {
try {
String[] command=new String[2];
command[0]="cmd /c start cmd.exe /k \"telnet\"";
command[1]="92.44.0.60";
Process p =Runtime.getRuntime().exec(command);
try {
p.waitFor();
} catch (InterruptedException e) {
System.out.println(e);
}
BufferedReader reader= new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
line=reader.readLine();
File file =new File("rapor.txt");
file.createNewFile();
FileWriter writer=new FileWriter(file);
StringBuilder responseData=new StringBuilder();
while(line!=null) {
System.out.println(line);
responseData.append(line);
writer.write(line);
writer.close();
}
BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream()) );
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while((Error=stdError.readLine())!=null) {
System.out.println(Error);
}
while((Error=stdInput.readLine())!=null) {
System.out.println(Error);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
i want to run telnet execute some commands i have two problem first when i connect to telnet it ask me username and password how ı contineude execute commands by using code after the enter password and my second question inputstream is not working readline is empty all time how can ı fix this problems.thanks for hel
I recommend you the Apache Commons Net Java library (http://commons.apache.org/proper/commons-net/) which contains various clients for many Internet protocols, including Telnet. I don't recommend you to use the embedded telnet client from the OS. Things will be cleaner with a library.
In addtion, in your first while loop, you're closing the writer object every iterations, and you don't read further with your reader.