Continuously Reading From Socket InputStream
Feb 26, 2014
I'm writing a really simple 1 on 1 chatting program thing using java.net.Socket and reading each other's messages b using writeUTF() and readUTF() of java.io.DataOutputStream and java.io.DataInputStream. Thing is, I wanna write a thread for both sides to continuously read from their respective socket's input streams while ignoring the lack of data coming through like when one user is not sending a message or something. I've written a dumbed down version of this that only reads one message from only one side and another one that sends a file, both of which work fine, I guess.
I'm using java.util.Scanner for user input, if that's acceptable, for I am not too familiar with Java's other readers. Also, I just started teaching myself about java.net.Socket, so I may not be too familiar other than the basics like how to set up a connection and how to send data using the getOutputStream() member function and stuff like that.
View Replies
ADVERTISEMENT
Dec 6, 2014
I'm trying to synchronize two folders and their sub directories between a client and a server. I have a modified version of this class which I've posted below. In my Client class, I create a WatchDir object and call its processEvents() method in an infinite loop. The method returns a myTuple object (a struct containing the event type and a path object) if an event is registered and null if not.
The problem is that this only seems to work for the first event to happen in the directory (i.e. if I add a file to the watched folder, my WatchDir object.processEvents() returns one Tuple with an ENTRY_CREATE event and never returns another Tuple for other file additions/deletions/modifications that happen after). I'd like for processEvents to be continuously called (hence the infinite while) returning a Tuple each time some event occurs.
My modified WatchDir:
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
[Code] ....
View Replies
View Related
Jul 22, 2014
So we have a Client and Server. Client opens a socket to Server, server initiates new Thread to handle the communication with client. Is there a way to be singnalled when there is input on socket, so I don't have to use infinite while loop solution?
View Replies
View Related
Nov 3, 2014
I'm having a lot of problems reading data from a socket. I'm trying to read the responses of a python server. I've a
BufferedReader inputStream = new BufferedReader( new InputStreamReader(socket.getInputStream()));
And then:
char[] messageChunk=new char[32768]; //32768
List<Byte> messageBytesList = new ArrayList<Byte>();
while (inputStream.ready()) {
inputStream.read(messageChunk, 0, 32768);
for(int k=0;k<32768;k++){
messageBytesList.add((byte)messageChunk[k]);
}
}
inside a thread. Then I convert the list of bytes to a byte array using:
Byte[] messageBytes = messageBytesList.toArray(new Byte[messageBytesList.size()]);
byte[] message = ArrayUtils.toPrimitive(messageBytes);
The problem is that I often receive ArrayOutOfBound errors when I try to parse the byte array. I think that I'm reading from the socket in a wrong way..
View Replies
View Related
Aug 5, 2014
I'm up to an app which includes Alarm clock in it. User selects the date using JSpinners and My Alarm clock class checks if the current date is equal to the selected date and pops up an alarm. That's all i've done so far. What i want is some ideas about how can i manage these alarms in my app. What i think is:
* Getting alarm dates from user and save it in database and creating a thread which runs always and check database whether there is an alarm... (will it make my app) ??
In simple words how to continuously check for upcoming alarms and popup any time any alarm comes up during my app is running
Note: My App is not only about alarms, it also contains a complete management system.
View Replies
View Related
Feb 3, 2014
I am writing a script for a program, now I am very new to Java. So, issue I am having is the program keeps clicking on the MM continuously. I just want it to click each spot 1 time.
Here is my code :
public class ToPortal implements Strategy {
Tile Portal = new Tile(2681, 2591);
Tile To = new Tile(2667, 2601);
[Code] ....
View Replies
View Related
Jul 11, 2014
I read that InputStream is used for byte based reading it reads 1 byte at a time.And InputStreamReader is used for charcter based reading so it reads one charcter at a time so no need to convert this first to int then read it.Here is reading using InputStream.
input=new FileInputStream("D:/input.txt");
int c;
while((c=input.read())!=-1)
{
System.out.print((char)c);
}
and here is reading using InputStreamReader
input=new FileInputStream("D:/input.txt");
reader=new InputStreamReader(input,"UTF-8");
int c;
while((c=reader.read())!=-1)
{
System.out.print((char)c);
}
so what is difference between InputStream and InputStreamReader in both case i have to use a Int and then read it and at the end if I want to print that data I have to cast that with "(char)c".So what is advantage of using InputStreamReader?
View Replies
View Related
Aug 23, 2014
I am new to programming in regards to I/O, channels, SSH, etc...
At the moment I am trying to transform the Shell.java program from the JCraft JSch examples; JSch - Java Secure Channel - Examples
The way in which I am trying to transform it is by instead of having the character input go into the channel automatically from the keyboard (refer to line 77 in Shell.java), I just want to pro-grammatically insert characters in to the channel at my discretion, so for example I have a string called unixCommand that I want to insert into the channel, and I don't want there to be any other way of inserting into the channel such as the standard input stream, so for example I'd have the statement <insert unixCommand to UNIX box at other side of channel> inserted somewhere after line 100 in Shell.java.
I was thinking that maybe I have to use some other InputStream object at line 77 when setting the channels input stream instead of System.in, but I am not sure how to do this (but really I'm not sure if I'm even on the right tracks?). I believe all this confusion may be down to a misunderstanding with the general concepts involved with channels and I/O ...
View Replies
View Related
Aug 23, 2014
I am trying to transform the Shell.java program from the JCraft JSch examples : [URL] ....
The way in which I am trying to transform it is by instead of having the character input go into the channel automatically from the keyboard (refer to line 77 in Shell.java), I just want to pro-grammatically insert characters in to the channel at my discretion, so for example I have a string called unixCommand that I want to insert into the channel, and I don't want there to be any other way of inserting into the channel such as the standard input stream, so for example I'd have the statement <insert unixCommand to UNIX box at other side of channel> inserted somewhere after line 100 in Shell.java.
I was thinking that maybe I have to use some other InputStream object at line 77 when setting the channels input stream instead of System.in, but I am not sure how to do this (but really I'm not sure if I'm even on the right tracks?). I believe all this confusion may be down to a misunderstanding with the general concepts involved with channels and I/O.
View Replies
View Related
Jul 26, 2014
I have the code below that just keeps getting the user's name and displaying it until the user enter's an empty string. Well, to simulate that, I just hit the keyboard instead of entering any name but for some reasons I am not seeing in my code, the programme just keeps looping.
System.out.println("Enter your name :
");
Scanner st = new Scanner(System.in);
while(st.hasNext()){
System.out.println("Enter your name :
");
String name = st.nextLine();
System.out.println(name);
if(name==" ") break;
}
System.out.println("you are out of the while loop now!!");
View Replies
View Related
Jun 27, 2014
I had a Rest web service call and get InputStream.Now i want to Write Input Stream to PrintWriter of servlet.So that it can be downloaded.I am able to write String and file can be downloaded using following code, i want it to work for Input streamFollowing is code:
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename="" + name + ".pdf"");
response.getWriter().write(is);
Write can take following:
write(String)
write(char[])
write(int)
write(String, int len, int off)
write(char[], int len, int off)
I think char[] will not harm PDF file which is going to download in it
View Replies
View Related
Dec 4, 2014
I have upgraded to myeclipse 10.7 ,java "com.sun.java.jdk.win32.x86_64_1.6.0.013" and Struts 2.1 (Right now using Struts 1.1 support) from myeclipse 10.7 ,java 1.4 and Struts 1.1. I installed jasperassistant 2.4.2 plug-in using jasperReports 2.0.2 (My old report files were using same version).
All files compile successfully in new environment but when I export I get following error Export to PDF
a. Reports having no crosstab
"Java.lang.NullPointerException"
b. Reports reports having crosstab
"Error loading object from InputStream"
java.io.InvalidClassException: net.sf.jasperreports.crosstabs.base.JRBaseCrosstabGroup;
Export to EXCEL
a. Reports having no crosstab
java.lang.NullPointerException
b.Reports reports having crosstab
java.lang.NullPointerException
All files are at correct location....
View Replies
View Related
Feb 20, 2014
I just wrote a small but working code to parse a multipart message with two files binary encoded.
Problem is, after splitting the content of the files is reduced to normal "alphabetic" digits, and i dont know why.
I just appended my source code and a test file ( multipart ). And the result of my parsing. (part_0 = json, part_1 = file, part_2 = file)
Unfortunately, i dont know, if the Spring FW provides an easier way of doing so at all. Haven't found it yet.
Java Code:
String requestUrl = "http://localhost:8888/";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
HttpEntity<String> entity = new HttpEntity<String>("test");
ResponseEntity<byte[]> response = restTemplate.exchange(requestUrl, HttpMethod.GET, entity, byte[].class);
[Code] .....
View Replies
View Related
Oct 8, 2014
Write a program that continuously asks for an alphabet letter, and stops when a non-alphabet letter is entered. Then output the number of upper case letters, lower case letters, and vowels entered ....
View Replies
View Related
Feb 13, 2014
I'm developing a web-based chatting system using JSP and socket.
The problem i am facing is that the sender can send message but on the receiver side we have to manually refresh the page. The sender stays into blocking mode until the receiver refresh its page !
after that i've implemented auto-refresh on the receiver side and "Connection Refused" exception is generated.
View Replies
View Related
Mar 4, 2014
Currently I have socket of the tcp version.
Java Code:
final ServerSocket serverSocketConn = new ServerSocket(9000);
while (true) {
try {
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
[Code] .....
I managed to convert this final DatagramSocket serverSocketConn = new DatagramSocket (9000);
Now I am stuck here
Socket socketConn1 = serverSocketConn.accept();
new Thread(new ConnectionHandler(socketConn1)).start();
Can I use this or I need to create a manual thread pooling for UDP ?
View Replies
View Related
May 22, 2014
I can have up to 100,000 simultaneous connections to a udp socket, which needs to be handled by separate threads. Each of the connections talk to a c program on an embedded device that sends and responds with an array of unsigned chars. Now Java does not have an unsigned char type. The closest you can use is a short. But DatagramPacket requires a byte argument:
public class Socket {
public Socket(int port) throws IOException {
new SocketThread().start();
} }
public class SocketThread extends Thread {
protected DatagramSocket socket = null;
[Code] .....
So how can I go about reading and writing unsigned chars over a udp socket?
View Replies
View Related
Apr 4, 2015
if i send messages as in the code below, is there a way to read only one message, if the client doesn't know how long it is (or if he only knows the maximum length)?in the documentation it says, that the method read(byte[]) reads until no data ist available or end of file is decteted. What does the latter mean? Can i extend the array that i sent by a byte that signals the end? Here is my Code:
Server
public class Server implements Runnable{
ServerSocket server;
HashMap<Short,Socket> clients;
public Server(){
clients = new HashMap<>();
[code]....
Both are startet in seperate threads. At the moment the first output of the client is "12 bytes read", and then continously "-1 bytes read"(because the server closes).
View Replies
View Related
Feb 10, 2014
I have been working with socket programming. I was trying to develop a two way communication from server to client. The data is being received when sent from server to client but there is a problem when I am sending from client to server.
I am getting an error as "Socket is closed" pointing to the line where I have created a BufferedReader. I have simplified some part of my code to be very specific.
Code attached.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
public static void main(String args[])
{
String id="policeone";
int hashcodeid=0;
[Code] ....
Error::
Receiving string from client: 'java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:872)
at Server.main(Server.java:51)
View Replies
View Related
Sep 21, 2014
I want to download objects (css , jpeg, html ,png ) using sockets in java without using httpurlconnection . How can i do this with simple socket library ?
View Replies
View Related
May 13, 2014
I got the below exception .how to resolve this .It's receiving the data up to 10 min then suddenly below error happening. I have embedded the source code below
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
[Code] .....
View Replies
View Related
Feb 13, 2014
I am new to JSP !! and I'm developing a web-based chatting system using JSP and socket.
The problem I am facing is that the sender can send message but on the receiver side we have to manually refresh the page. The sender stays into blocking mode until the receiver refresh its page !
After that I've implemented auto-refresh on the receiver side and "Connection Refused" exception is generated.
View Replies
View Related
Sep 26, 2014
I am trying to download object thorugh sockets in java . My code is
String servername = "http://ea-cdn.voxmedia.com"; //(String) innObj.get("value");
String filename = "http://ea-cdn.voxmedia.com/production/vox-40-maps/stylesheets/styles-358f0375.css"; //(String) request.get("url");
Socket socket = new Socket("http://10.10.78.62", 3128);
DataOutputStream bw = new DataOutputStream(
[code]...
View Replies
View Related
Sep 2, 2014
i was reading my book when in a code,it used accept(),but it did'nt talk about it.would you explain to me where to use accept().(the chapter was about socket programming)
View Replies
View Related
Feb 18, 2014
I'm trying to send a text file over a socket, from client to server, but I doesn't work. I will demonstrate a part of the code that isn't working.
The critical part of the server look like this:
while(true) {
try {
Socket socket = fileSocket.accept();
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = in.readLine();
And the client like this:
Socket = new Socket(address, number);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(Socket.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(Socket.getInputStream()));
BufferedReader fileIn = new BufferedReader(new FileReader(filename));
String s = fileIn.readLine();
out.write(s);
Now I want the s in the server to hold the same string as s in the client, but the server can't read the stream - nothing happens. I know that readLine() reads until a new line character, but it doesn't word to write and read a single character either.
View Replies
View Related
Dec 7, 2014
I have an android device which i want to be able to switch off remotely from a console hosted on the amazon cloud.The console is a simple html button that on click sends a command to a listening server on an android device that i know its ip address.
My question,is this even possible given the huge security bleach this would present to rogue apps to be able to order actions on remote devices not started by the device owner?.
The way i know the ip is via once internet is connected on an android deice,i shall then make it announce its ip that it has been assigned by the service provider,then starting a server to accept external connections.
My theory could be wrong if what i want is not permitted.
View Replies
View Related