Java: Server not receiveing messages over tcp socket more than once. - java

A Client(botnet server) is trying to send continuous messages over TCP socket to a server(disruptor), but only one message is received at the disruptor. Disruptor is a thread which is created by the botnet server.
code: Botnet server
public static void main(String[] args) {
// TODO Auto-generated method stub
Jedis jedis = new Jedis("localhost");
String pattern = new String("TKproject");
input = new Disruptor(30001,1024,jedis,pattern);
int count = 0;
Thread start = new Thread(input);
start.start();
try {
request = new Socket("localhost",30001);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Random rand = new Random();
Message msg = new Message();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(request.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
System.out.println("count is : " + count);
count++;
if(count == 5)
break;
if(count % 15 == 0)
jedis.rpush(pattern,Integer.toString(count));
int next = rand.nextInt(3);
msg.setMessageId(count);
switch (next){
case 0: msg.setType(MessageType.HELLO);
break;
case 1: msg.setType(MessageType.REQUEST);
break;
case 2: msg.setType(MessageType.REPLY);
break;
default: msg.setType(MessageType.REQUEST);
break;
}
//System.out.println("Message id "+msg.Messageid);
try {
oos.writeObject(msg);
//oos.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Disruptor run()
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println("Disruptor Running");
Socket receipt = null;
try {
receipt = server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectInputStream recv = null;
try {
recv = new ObjectInputStream(receipt.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
byte [] rcvbytes = new byte[2048];
try {
recv.read(rcvbytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
storage.write((Message)recv.readObject());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

receipt = server.accept();
You need to perform this just once to connect your server to a client, try and move that instruction before the while(true).
The same needs to be done for the ObjectInputStream declaration.

Either:
send a new Message object each time instead of refreshing the old one
send it using `writeUnshared()’, or
call ObjectOutputStream.reset() before sending a refreshed Message object.

Related

my chat client is only connecting to local host

I have coded the following client which is only connecting to the local host, the ip on which the machine is connected, but not a server running on different ip on a different machine.
The error I get when I connect to outside is Connection refused
How to make it connect outside local host?
My code is as follows
public ChatClient(JTextField address, JTextField port, JTextField user,
JTextField text, JTextArea tapane3, JTextArea tapane4) {
// TODO Auto-generated constructor stub
this.address=address;
this.user=user;
this.text=text;
this.port=port;
add=address.getText();
textarea=tapane3;
showusers=tapane4;
}
public void sendToPort(String str) throws IOException {
Socket socket = null;
//String str = "Hello World";
try {
out.write(str, 0, str.length());
out.flush();
} catch (IOException e) {
System.err.print(e);
} finally {
}
}
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Send"))
{
try {
textarea.append(SendMessage()+"\n");
System.out.println(SendMessage());
sendToPort("x");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Connect"))
{
try {
String prt=port.getText();
cs = new Socket(add, Integer.parseInt(prt));
out =new OutputStreamWriter(cs.getOutputStream(), "UTF-8");
showusers.setText(user.getText());
//sendToPort(Integer.parseInt(prt), Address);
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getActionCommand().equals("Disconnect"))
{
try {
cs.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void Connect() throws NumberFormatException, UnknownHostException, IOException {
// TODO Auto-generated method stub
}
public String SendMessage() {
// TODO Auto-generated method stub
{
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String getdate=(dateFormat.format(date));
String content = text.getText();
String from = String.format(user.getText());
String all = "START:" + getdate + ":" + from + ":"+"MESSAGE:" + content + ":END";
//textarea.setText(all);
try {
out.write(all);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return all;
}

The code works on java runtime but doesn't works on android

this code works correctly on Java runtime.
public static void main(String[] args) {
// TODO Auto-generated method stub
extendedList array=new extendedList();//extendedList:class extendedList extends ArrayList<XXX> implements Serializable
//....unimportant code...
FileOutputStream out;
ObjectOutputStream oout;
try {
out=new FileOutputStream("Data.dat");
oout=new ObjectOutputStream(out);
oout.writeObject(array);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fin;
ObjectInputStream ofin;
try {
fin=new FileInputStream("Data.dat");
ofin=new ObjectInputStream(fin);
extendedList ret=(extendedList) ofin.readObject();
for(int i=0;i<ret.size();i++)
System.out.print(ret.get(i).getnum()+":"+ret.get(i).getename()+":"+ret.get(i).getfname()+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but when I want to read Data.dat in android.it throws ClassNotFoundException.What is wrong?
ObjectInputStream object;
InputStream input;
try {
Log.d("adapter","befor Open");
input=assets.open("Data.dat");
Log.d("adapter","after Open");
object= new ObjectInputStream(input);
Array=(extendedList) object.readObject();
//........hidden code
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("adapter","IOException has detected");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
Log.d("adapter","ClassNotFoundException has detected");
e.printStackTrace();
}
also when I replace InputStream with FileInputStream and cast asset.open("Data.dat").when debugger arrive to that line.Source not found occurs.

Which copy data more faster in Java while using FileChannel.transferFrom and while()?

The following Java code in two ways to copy files which more efficient? Want to be able to explain why, thank you.
By the way, I've tested the same file which size is about 300 megabytes. The speed of the first method as fast as the second one. But after tested more times, the result is differently.
One of my test result as below:
NO.1: Using transferFrom took 3396ms
NO.1: Using while took 3334ms
NO.2: Using transferFrom took 4239ms
NO.2: Using while took 3225ms
NO.3: Using transferFrom took 3906ms
NO.3: Using while took 4153ms
NO.4: Using transferFrom took 3100ms
NO.4: Using while took 3174ms
NO.5: Using transferFrom took 3156ms
NO.5: Using while took 3180ms
Code:
public void copyData(String inPath, String outPath1, String outPath2) {
FileChannel inChannel = null;
FileChannel outChannel = null;
FileInputStream fin = null;
FileOutputStream fout = null;
File out1File = null;
File out2File = null;
int bufferLen = 20480 * 2 * 1024;
long runTime;
ByteBuffer bb = ByteBuffer.allocateDirect(bufferLen);
for (int i = 0; i < 5; i++) {
try {
fin = new FileInputStream(new File(inPath));
out1File = new File(outPath1);
fout = new FileOutputStream(out1File);
inChannel = fin.getChannel();
outChannel = fout.getChannel();
runTime = System.currentTimeMillis();
outChannel.transferFrom(inChannel, 0, inChannel.size());
runTime = System.currentTimeMillis() - runTime;
System.out.println("NO." + (i + 1) + ": "
+ "Using transferFrom took " + runTime + "ms");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != inChannel) {
try {
inChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outChannel) {
try {
outChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out1File.deleteOnExit();
}
/**********************************************************/
try {
fin = new FileInputStream(new File(inPath));
out2File = new File(outPath2);
fout = new FileOutputStream(out2File);
inChannel = fin.getChannel();
outChannel = fout.getChannel();
runTime = System.currentTimeMillis();
while (true) {
int ret = inChannel.read(bb);
if (ret == -1) {
break;
}
bb.flip();
outChannel.write(bb);
bb.clear();
}
runTime = System.currentTimeMillis() - runTime;
System.out.println("NO." + (i + 1) + ": " + "Using while took "
+ runTime + "ms");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != inChannel) {
try {
inChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != outChannel) {
try {
outChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out2File.deleteOnExit();
}
}
}

Java Client Server "Socket is closed"

I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !

Android : My app crashes when there is a blank editText field

I have a problem with my code.
It keeps on crashing when i have a blank editText field.
This bit of code is in the settings of my app and works the data fine but when there is a blank field it crashes the program.
Here's the code for it.
Please don't be harsh because it is my 1st android app. So if anyone knows how to solves the blank edit text field problem that would be greatly appreciated! (Any other comments on how to improve the app would be a help to).
Cheers
package com.cleanyet.cyv100fp;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class sTasks extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tasks);
/*Sets Up the Variables*/
Button done = (Button) findViewById(R.id.done1);
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = null;
String task2 = null;
String task3 = null;
String task4 = null;
String task5 = null;
String edit = "Edit Task";
/*Fixes the Blank Field bug*/
/*Sets up the file input*/
FileInputStream fis = null;
/*Gets the tasks set previously*/
/*Task 1 set up*/
try {
fis = openFileInput(FILENAME1);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task1 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
/*Task 2 set up*/
try {
fis = openFileInput(FILENAME2);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task2 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task2.toString().length() < 0) {
task2.toString();
t2.setText(task2);
}
else {
t2.setText(edit);
}
/*Task 3 set up*/
try {
fis = openFileInput(FILENAME3);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task3 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task3.toString().length() < 0) {
task3.toString();
t3.setText(task3);
}
else {
t3.setText(edit);
}
/*Task 4 set up*/
try {
fis = openFileInput(FILENAME4);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task4 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task4.toString().length() < 0) {
task4.toString();
t4.setText(task4);
}
else {
t4.setText(edit);
}
/*Task 5 set up*/
try {
fis = openFileInput(FILENAME5);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
task5 = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (task5.toString().length() < 0) {
task5.toString();
t5.setText(task5);
}
else {
t5.setText(edit);
}
/*When changes have been made and done is clicked*/
done.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/*Sets up the Variables*/
EditText t1 = (EditText)findViewById(R.id.tbTask1);
EditText t2 = (EditText)findViewById(R.id.tbTask2);
EditText t3 = (EditText)findViewById(R.id.tbTask3);
EditText t4 = (EditText)findViewById(R.id.tbTask4);
EditText t5 = (EditText)findViewById(R.id.tbTask5);
String tasks1 = t1.getText().toString();
String tasks2 = t2.getText().toString();
String tasks3 = t3.getText().toString();
String tasks4 = t4.getText().toString();
String tasks5 = t5.getText().toString();
String FILENAME1 = "stask1";
String FILENAME2 = "stask2";
String FILENAME3 = "stask3";
String FILENAME4 = "stask4";
String FILENAME5 = "stask5";
String task1 = tasks1;
String task2 = tasks2;
String task3 = tasks3;
String task4 = tasks4;
String task5 = tasks5;
String edit = "Go to settings to make this task.";
if (t1 != null){
t1.setText(edit);
/*t2.setText(edit);
t3.setText(edit);
t4.setText(edit);
t5.setText(edit);*/
};
/*Put if statement here to catch the empty field*/
/*Makes The Changes to the Tasks*/
try {
FileOutputStream fos1 = openFileOutput(FILENAME1, Context.MODE_PRIVATE);
fos1.write(task1.getBytes());
fos1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos2 = openFileOutput(FILENAME2, Context.MODE_PRIVATE);
fos2.write(task2.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos3 = openFileOutput(FILENAME3, Context.MODE_PRIVATE);
fos3.write(task3.getBytes());
fos3.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos4 = openFileOutput(FILENAME4, Context.MODE_PRIVATE);
fos4.write(task4.getBytes());
fos4.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos5 = openFileOutput(FILENAME5, Context.MODE_PRIVATE);
fos5.write(task5.getBytes());
fos5.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent("com.checkin.cyv100fp.settings"));
}
});
}
}
if (task1.toString().length() < 0) {
task1.toString();
t1.setText(task1);
}
else {
t1.setText(edit);
}
The above makes no sense at all.
Firstly task1 IS a string so there's no need to call toString() to convert it to one.
Secondly, your conditional statement (if) is checking to see if task1 has a length less than zero....think about it.
Thirdly, if it does have an impossible length less than zero you then call toString() on it again (with no variable to receive the impossible less than zero result) and you then try to set the text of your t1 EditText.
The chances are that your file reading is failing (probably because you only save the strings later in the onClick(...) method). Because your task strings will be null if the file reading fails then you need to test for null before trying to use them.
In other words you're doing this in your code...
String task1 = null;
To fix the bit of code I enclosed at the beginning, use...
if (task1 != null) {
t1.setText(task1);
}
else {
t1.setText(edit);
}
...but most importantly, make sure your files have the strings in them that you need to read.

Categories