This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
I am developing a multiplayer snake game. The game seems to be running fine except it often(not every time) randomly throws the java.io.StreamCorrupted Exception type code :AC
The full StackTrace of the same is given below.
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at mycode.ConnectionManager.otherRunMethod(ConnectionManager.java:231)
at mycode.ConnectionManager$1.run(ConnectionManager.java:289)
at java.lang.Thread.run(Unknown Source)
The Client side code where the error is generated is given below:
void otherRunMethod() {
try {
while (true) {
boolean gameup = false;
objin = new ObjectInputStream(socket.getInputStream());
Object insnake = objin.readObject();
if (((Snake) insnake).player.length() >= 9) {
if (((Snake) insnake).player.substring(0, 8).equals(
"Resigned")) {
String[] s = ((Snake) insnake).player.split(",");
map.remove(s[1]);
continue;
} else if (((Snake)insnake).player.substring(0, 10)
.equals("food_eaten")) {
String[] s = ((Snake) insnake).player.split(",");
Game.foodx = Integer.parseInt(s[1]);
Game.foody = Integer.parseInt(s[2]) + 35;
objin = new ObjectInputStream(socket.getInputStream());
insnake = objin.readObject();
if(((Snake)insnake).score>highestscore){
highestscore=((Snake)insnake).score;
if(highestscore>=100 && highestscore<200)
levelUp(2);
else if(highestscore>=200){
levelUp(4);
}
}
if (s.length == 4) {
System.out.println(s[3]);
if (s[3].equals("game_up")) {
gameup=true;
}
}
}
}
Snake temp = new Snake((Snake) insnake);
map.remove(temp.player);
map.put(temp.player, temp);
if(temp.gameover){
allPlayersEliminated();
}
findPos();
game_UpCheck(gameup);
Thread.sleep(10);
}
} catch (java.net.SocketException s) {
JOptionPane.showMessageDialog(null, "Server Closed", "ERROR",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
The corresponding server side code for the same is as follows:
void relay(Snake move) {
boolean foodeaten = false;
Snake snake = move;
try {
if (move != null && move.player.length() > 9) {
if (move.player.equals("food_eaten")) {
move.player = move.player + ","
+ (Snakeserver.randomGenerator.nextInt(100) * 6)
+ ","
+ (Snakeserver.randomGenerator.nextInt(100) * 6);
foodeaten = true;
snake = (Snake) objin.readObject();
int rows = Snakeserver.score.getModel().getRowCount();
int row = 1;
for (int i = 0; i < rows; i++) {
if (((Snake) snake).player
.equals((String) Snakeserver.score.getModel()
.getValueAt(i, 0))) {
row = i;
break;
}
}
if (snake.score >= 300)
move.player += "," + "game_up";
Snakeserver.score.getModel()
.setValueAt(snake.score, row, 1);
}
}
if (move.gameover) {
int rows = Snakeserver.score.getModel().getRowCount();
int row = 1;
for (int i = 0; i < rows; i++) {
if (snake.player.equals((String) Snakeserver.score
.getModel().getValueAt(i, 0))) {
row = i;
break;
}
}
Object temp = Snakeserver.score.getModel().getValueAt(row,
1);
temp += " GAME OVER";
Snakeserver.score.getModel().setValueAt(temp, row, 1);
}
for (Snake name : map.keySet()) {
if (name != null) {
if (name.player.equals(snake.player)) {
name.copyValues(snake);
}
objout = new ObjectOutputStream(map.get(name)
.getOutputStream());
objout.writeObject(move);
objout.flush();
if (foodeaten) {
objout = new ObjectOutputStream(map.get(name)
.getOutputStream());
objout.writeObject(snake);
objout.flush();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Actually I don't know where the problem lies so I have perhaps dumped more code than necessary.
I finally found the solution to my problem after digging around for a few hours.
In the server side code see the following piece of code:
for (Snake name : map.keySet()) {
if (name != null) {
if (name.player.equals(snake.player)) {
name.copyValues(snake);
}
objout = new ObjectOutputStream(map.get(name)
.getOutputStream());
objout.writeObject(move);
objout.flush();
//rest of code goes here. Closing brackets as above.
If I write the line
objout = new ObjectOutputStream(map.get(name).getOutputStream());
before the compound statement
if (name.player.equals(snake.player)) {
name.copyValues(snake);
}
I seem to get rid of the StreamCorrupted Exception.
Any suggestions as to why this is happening would be most welcome.
I too faced same exception and issue as explained above, was,
while writing(sending) msg(object), I was creating new OutputObjectStream, as below
//client or server side
while(true)
{
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
out.writeObject(some_msg_object);
}
/* but while reading(receiving), I was not creating new inputObjectReader
ie */
//on other side
while(true)
Message msgReceived = (Message)inputObjectReader.readObject();
and this resulted above exact same education,
therefore, if sending msg, by creating new OutputStream, receive it by creating new InputStream viceversa, is sending using same already created OutputStream receive by already created InputStream.....
Related
So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
I want to take real-time data using modbus tcp/ip simulator for filling of a tank that uses port no 502.
How can I write a code in java to get the holding register value from the simulator and also I want to control the values of it?
If you use a Modbus library like this one most of the work is already done for you.
ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost").build();
ModbusTcpMaster master = new ModbusTcpMaster(config);
CompletableFuture<ReadHoldingRegistersResponse> future =
master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
future.thenAccept(response -> {
System.out.println("Response: " + ByteBufUtil.hexDump(response.getRegisters()));
ReferenceCountUtil.release(response);
});
import java.io.* ;
import java.net.* ;
import java.util.*;
public class Modcli {
public static void main(String argv[]) {
if (argv.length < 4) {
System.out.println("usage: java test3 dns_name unit reg_no num_regs");
System.out.println("eg java test3 aswales8.modicon.com 5 0 10");
return;
}
try {
String ip_adrs = argv[0];
int unit = Integer.parseInt(argv[1]);
int reg_no = Integer.parseInt(argv[2]);
int num_regs = Integer.parseInt(argv[3]);
System.out.println("ip_adrs = "+ip_adrs+" unit = "+unit+" reg_no = "+
reg_no+" num_regs = "+num_regs);
// set up socket
Socket es = new Socket(ip_adrs,502);
OutputStream os= es.getOutputStream();
FilterInputStream is = new BufferedInputStream(es.getInputStream());
byte obuf[] = new byte[261];
byte ibuf[] = new byte[261];
int c = 0;
int i;
// build request of form 0 0 0 0 0 6 ui 3 rr rr nn nn
for (i=0;i<5;i++) obuf[i] = 0;
obuf[5] = 6;
obuf[6] = (byte)unit;
obuf[7] = 3;
obuf[8] = (byte)(reg_no >> 8);
obuf[9] = (byte)(reg_no & 0xff);
obuf[10] = (byte)(num_regs >> 8);
obuf[11] = (byte)(num_regs & 0xff);
// send request
os.write(obuf, 0, 12);
// read response
i = is.read(ibuf, 0, 261);
if (i<9) {
if (i==0) {
System.out.println("unexpected close of connection at remote end");
} else {
System.out.println("response was too short - "+i+" chars");
}
} else if (0 != (ibuf[7] & 0x80)) {
System.out.println("MODBUS exception response - type "+ibuf[8]);
} else if (i != (9+2*num_regs)) {
System.out.println("incorrect response size is "+i+
" expected"+(9+2*num_regs));
} else {
for (i=0;i<=2;i++) {
int w = (ibuf[0+i+i]<<8) + ibuf[1+i+i];
System.out.println("word "+i+" = "+w);
}
for (i=3;i<=5;i++) {
int w = (ibuf[i+3]) ;
System.out.println("word "+i+" = "+w);
}
for (i=0;i<num_regs;i++) {
int w = (ibuf[9+i+i]<<8) + ibuf[10+i+i];
System.out.println("word "+i+" = "+w);
}
}
// close down
es.close();
} catch (Exception e) {
System.out.println("exception :"+e);
}
}
}
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
I seem to be having a problem reading the file and it is in the same directory as the source. I am using eclipse. I was wondering why it can't find the file.
Could not read the file
java.io.FileNotFoundException: Simulation.Configuration (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at hw1.Simulator.main(Simulator.java:24)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Simulates the interaction between objects
*/
public class Simulator {
public static void main(String[] args) {
ArrayList<Geotask> geotasks = new ArrayList<Geotask>();
int dimensionX = 0;
int dimensionY = 0;
int numberOfMobileObjects = 0;
MobileObject[] MoblieObjects = new MobileObject[numberOfMobileObjects];
int durationOfSimulation = 0;
try {
Scanner in = new Scanner( new FileReader("Simulation.Configuration"));
while (in.hasNext()) {
String simulation = in.next();
switch (simulation) {
case ("dimensionX:"):
dimensionX = in.nextInt();
break;
case ("dimensionY:"):
dimensionY = in.nextInt();
break;
case ("numberOfMoileObjects:"):
numberOfMobileObjects = in.nextInt();
break;
case ("WarningGeotask:"):
Geotask wTask = new WarningGeotask(in.nextInt(),
in.nextInt());
geotasks.add(wTask);
break;
case ("CounterGeotask:"):
Geotask cTask = new CounterGeotask(in.nextInt(),
in.nextInt());
geotasks.add(cTask);
break;
case ("PopulationMonitoringGeotask:"):
Geotask pTask = new PopulationMonitoringGeotask(
in.nextInt(), in.nextInt(), in.nextInt());
geotasks.add(pTask);
break;
case ("durationOfsimulation:"):
durationOfSimulation = in.nextInt();
break;
}
}
in.close();
System.out.println("unable to close configuration file!!!");
Ground ground = new Ground(dimensionX, dimensionY);
MobileObject mobile = null;
for (Geotask tsk : geotasks) {
ground.addGeotask(tsk);
}
for (int i = 0; i < numberOfMobileObjects; i++) {
mobile = new MobileObject(i, i % dimensionX, i % dimensionY, 1,
i % 8, ground);
MoblieObjects[i] = mobile;
for (Geotask tsk : geotasks) {
if (mobile.getCurrentX() == tsk.getX()
&& mobile.getCurrentY() == tsk.getY()) {
tsk.moveIn(mobile);
}
}
}
for (int i = 0; i < durationOfSimulation; i++) {
for (MobileObject obj : MoblieObjects) {
obj.move();
System.out.println("" + obj.getID() + " ( "
+ obj.getCurrentX() + ", " + obj.getCurrentY()
+ " )");
}
}
for (Geotask tsk : geotasks) {
tsk.printType();
}
} catch (FileNotFoundException e) {
System.out.println("Could not read the file");
}catch(NullPointerException e)
{
System.out.println("Null point exception");
}catch(IllegalArgumentException e)
{
System.out.println("Illegal Argument Exception");
}catch(IllegalStateException e)
{
System.out.println("Illegal State Exception");
}
}
}
Use
new InputStreamReader(Simulator.class.getResourceAsStream("Simulation.Configuration"));
You can return the directory of the program at run-time, which makes it OS independent.
System.out.printf("%s", System.getProperty("user.dir"));
SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.