I have two computers running this code:
import java.io.*;
import java.util.*;
import gnu.io.*;
public class Deb implements SerialPortEventListener, Runnable{
public static final int TIMEOUTSECONDS = 30;
public static final int BAUD = 9600;
static String telefono;
static Boolean llamar = false;
CommPortIdentifier cpiModem = null;
SerialPort modem;
BufferedReader is;
PrintStream os;
Thread hiloMarcado;
int nConnects = 0;
boolean flag = false;
String line;
public static void main(String argv[]) throws PortInUseException, UnsupportedCommOperationException, IOException, InterruptedException, TooManyListenersException {
if (argv.length>0) {
telefono = argv[0];
llamar = true;
}
new Deb();
}
public Deb() throws PortInUseException, UnsupportedCommOperationException, IOException, InterruptedException, TooManyListenersException{
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
while (pList.hasMoreElements()) {
CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();
if (cpi.getPortType()==CommPortIdentifier.PORT_SERIAL) {
SerialPort puertoSerie = (SerialPort) cpi.open("DEB", TIMEOUTSECONDS * 1000);
puertoSerie.setSerialPortParams(BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
puertoSerie.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN & SerialPort.FLOWCONTROL_RTSCTS_OUT);
BufferedReader is = new BufferedReader(new InputStreamReader(puertoSerie.getInputStream()));
PrintStream os = new PrintStream(puertoSerie.getOutputStream(), true);
os.println("AT");
Thread.sleep(TIMEOUTSECONDS * 50);
if (!is.ready()) {
System.out.println("No hay un modem en " + cpi.getName());
} else {
System.out.println("Hay un modem en " + cpi.getName());
cpiModem = cpi;
}
puertoSerie.close();
}
}
modem = (SerialPort) cpiModem.open("DEBita", TIMEOUTSECONDS * 1000);
modem.setSerialPortParams(BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
modem.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN & SerialPort.FLOWCONTROL_RTSCTS_OUT);
is = new BufferedReader(new InputStreamReader(modem.getInputStream()));
os = new PrintStream(modem.getOutputStream(), true);
modem.addEventListener(this);
modem.notifyOnDataAvailable(true);
modem.notifyOnCarrierDetect(true);
modem.notifyOnBreakInterrupt(true);
modem.notifyOnCTS(true);
modem.notifyOnDSR(true);
modem.notifyOnFramingError(true);
modem.notifyOnOutputEmpty(true);
modem.notifyOnOverrunError(true);
modem.notifyOnParityError(true);
modem.notifyOnRingIndicator(true);
/*System.out.println(is.read());*/
if (llamar) {
hiloMarcado = new Thread(this);
hiloMarcado.start();
}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.DSR:
System.out.println("Data Set Ready.");
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
System.out.println("Ignored event");
break;
case SerialPortEvent.BI:
System.out.println("Break Interrupt");
break;
case SerialPortEvent.CTS:
System.out.println("Clear to send");
break;
case SerialPortEvent.RI:
System.out.println("Pick up the receiver.");
if( event.getNewValue() )
{
System.out.println("Ring Indicator On");
}
else
{
System.out.println("Ring Indicator Off");
}
break;
case SerialPortEvent.CD:
if (event.getNewValue()) {
System.out.println("Connected");
nConnects = nConnects + 1;
} else {
System.out.println("Disconnected");
}
break;
case SerialPortEvent.DATA_AVAILABLE:
handleData();
break;
}
}
public void run() {
while (true) {
if (nConnects == 0) {
try {
if (!modem.isCD()) {
System.err.println("Estamos llamando ...");
os.println("ATDT" + telefono);
}
Thread.sleep(TIMEOUTSECONDS * 2000);
} catch (Exception ex) {
System.err.println("Failed to write message");
}
}
}
}
public void handleData() {
try {
int avail = modem.getInputStream().available();
byte[] response = new byte[avail];
StringBuffer strbuf = new StringBuffer();
modem.getInputStream().read(response, 0, avail);
if (!flag) {
modem.getInputStream().read(response, 0, avail);
for (int i = 0; i < avail; i++) {
Thread.sleep(5);
os.write((char) response[i]);
System.out.print((char) response[i]);
}
}
} catch (IOException ie1) {
System.out.println("File " + ie1);
} catch (InterruptedException in) {
System.out.println("Interrupt " + in);
}
}
}
It isn't the final version, I'm only seeing how it works. The thing is that when I use this code to dial to a phone number, for example, my mobile phone, it works, but it doesn't work the other way round; that is, calling from my number and acting the programme as a listener. I tried also with 2 computers, neither of them get the calls from the other end. Am I doing something wrong? I would appreciate any help.
AT-compatible modems should send a “RING” over the data line to notify you of an incoming ring event. Maybe you could listen for that?
Related
When the code reaches the InputStream.read(), the application becomes iresponsive.
I think maybe that is the case because the client code runs before the server code and it waits for the input.
Here is the server code
When login button is clicked then the case is "Send login details"(It sends the login details to the client) and if the id and password is correct then the case becomes**"Login successful". It is sending correct value in **output.readUTF();
public void doWork(String line) {
Connection conn = Main.getConnection();
switch (line) {
case "Send login details":
Main main = new Main();
String details = main.giveLoginDetails();
String id = " ";
String password = " ";
int i = 0;
while (details.charAt(i) != ' ') {
id = id + details.charAt(i);
i++;
}
try {
id = id.trim();
password = details.substring(i + 1);
System.out.println(id + " " + password);
output.writeUTF(id + " " + password);
}
catch (IOException e)
{
e.printStackTrace();
}break;
case "Login successful":
String getDet1 = "SELECT * FROM $t;";
if(su == 1)
getDet1 = getDet1.replace("$t", "Post1");
else
getDet1 = getDet1.replace("$t", "Post"+(su*10+1));
System.out.print(getDet1);
rs2 = stmt2.executeQuery(getDet1);
String d;
int dd;
for (int x = 0; x < ch; x++) {
rs2.next();
d = rs2.getString(2);
output.writeUTF(d);
System.out.println(d);
dd = rs2.getInt(3);
output.writeInt(dd);
System.out.println(dd);
d = rs2.getString(4);
output.writeUTF(d);
System.out.println(d);
d = rs2.getString(5);
// if(d == null) {
// output.writeUTF("null");
// System.out.println("null");
// }
// else
output.writeUTF(d);
// System.out.println(d+"not null ");}
}
}
catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
}
}
Client code:- Another scene after the login scene.
It is the Initialize method of Initializable interface. Here i am reading the output but it hangs.
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
String posts = "";
int ch = 0;
Main m = new Main();
Stage stage = m.getStage();
stage.setResizable(true);
int c = 0;
try {
posts = Networking.input.readUTF();
ch = Networking.input.readInt();
}
catch (IOException e)
{
e.printStackTrace();
}
int rs = Integer.valueOf(posts);
for(int k = 0; k<rs; k++) {
c++;
}
try {
Networking.input.readUTF();
}
catch (IOException e)
{
e.printStackTrace();
}
String det = "";
int cl;
for (int i = 0; i < ch; i++) {
a[i].setDisable(false);
a[i].setOpacity(1);
try {
Networking.output.writeUTF("send voting details");
det = Networking.input.readUTF();
System.out.println(det);
cl = Networking.input.readInt();
System.out.println(cl);
det = Networking.input.readUTF();
System.out.println(det);
det = Networking.input.readUTF();
System.out.println(det);
}
catch (IOException exx)
{
exx.printStackTrace();
}
}
}
Add:
Here is my Networking class
package sample;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Networking {
public static ServerSocket serverSocket= null;
public static void connect(int port)
{
try
{
serverSocket = new ServerSocket(port);
System.out.print("Server is started");
while (true)
{
Socket socket = null;
try {
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
Thread thread = new ServerThread(socket, input, output);
thread.start();
System.out.print("Client Accepted");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch(IOException exception)
{
exception.printStackTrace();
}
}
}
Using eclipse and java how to read the data from the pcb board with a serial cable, because the data of the pcb board arrive via cable in binary format. How to save the data that will be displayed in the compiler?
Someone help me please.
Below is the code I am writing to do this, but it does not detect any port when I plug in the serial cable
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort ="COM 1" ;
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print("The Read Bytes from SerialPort are");
System.out.write(readBuffer);
System.out.println();
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
Log Result:
port COM 1 not found.
The port names don't have spaces in them. Try changing:
String defaultPort ="COM 1" ;
to:
String defaultPort ="COM1" ;
i couldn't find any article upon "place call using java with a HSDPA Dongle" on google. i have done port initialization but don't know what to do for placing call.
1) i am using Huawei Dongle.
2) I have found error "NO CARRIER".
3) i am using the following code to detect port or modem and trying to place call but its giving me "NO CARRIER" error ! what mistake i am doing here kindly help me please
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void dial(String phoneNumber) {
try {
//dial to this phone number
messageString = "ATD" + phoneNumber + ";\r\n";
outputStream.write(messageString.getBytes());
System.out.println("Called ");
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void welcomeMessage(){
// open the sound file as a Java input stream
String gongFile = "C:\\Users\\SACHIN\\Desktop\\7001110.mp3";
InputStream in;
try {
in = new FileInputStream(gongFile);
// create an audiostream from the inputstream
// AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
// AudioPlayer.player.start(audioStream);
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
Main.class.getResourceAsStream(gongFile));
clip.open(inputStream);
clip.start();
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
System.out.println("Ringing");
/*try {
Thread.sleep(5000);
send("ATA");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
welcomeMessage();
}
}
//readBufferTrial=readBufferTria;//+new String(readBuffer)+new Date();
//print response message
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
System.out.println("Before Auto Answer");
gsm.send("ATS0=1");
Thread.sleep(1000);
gsm.dial("87SSSXXX9105");
// Thread.sleep(1000);
// gsm.welcomeMessage();
// Thread.sleep(1000);
// gsm.welcomeMessage();// for turning on Echo ATE1&W
Thread.sleep(20000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
First you have to check if your HSDPA dongle really supports calls. A lot of HSDPA sticks only support SMS and data.
If it does and you have e.g. a virtual serial port you can connect from your Java program to it using e.g. Java RXTX and send AT-Commands like ATDT01234567 (dial 01234567) to the stick.
I saw that there are a lot of question with the serial i/o operation so i decided to share a snippet of my code in which i read serial data from a serial port with the RXTX library.
This class read wait when there are data on the serial port and printed it.The class also save data in a String named data which can be obtained from another class
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static String data = "";
public static String getData() {
return data;
}
public static void setData(String data) {
SimpleRead.data = data;
}
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
// if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
}
}
}
}
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {System.out.println(e);}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {System.out.println(e);}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println(e);}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {System.out.println(e);}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
String data1="";
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
data1=data1+(String) numBytes;
}
setData(data1)
System.out.print(new String(readBuffer));
} catch (IOException e) {System.out.println(e);}
break;
}
}
}
The code for readig data from the serial port into another class
SimpleRead simpleRead=new SimpleRead;
String finalData="";
simpleRead.run();
finalData=simpleRead.getData()
I have a piece of code that connects a client to my server. However, every time I connect a client to the server it controls the same player instead of creating a new player. I think it is because I am not creating a new thread for every new client. If someone could show me how to create a new thread for every client that joins using the code I have already written.
import java.net.*;
import java.io.*;
public class Client extends PlayGame
{
public static void main(String [] args)
{
//String serverName = args[0];
//int port = Integer.parseInt(args[1]);
String serverName = "localhost";
int port = 40004;
//while (true ) {
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
//out.writeUTF("Hello from " + client.getLocalSocketAddress());
//DataInputStream in = new DataInputStream(inFromServer);
//System.out.println("Server says " + in.readUTF());
PlayGame game = new PlayGame();
//System.out.println("Do you want to load a specitic map?");
//System.out.println("Press enter for default map");
//game.selectMap(game.readUserInput());
//System.out.println("You may now use MOVE, LOOK, QUIT and any other legal commands");
String input = game.readUserInput();
while (input != "quit") {
out.writeUTF( input );
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server Response:\n" + in.readUTF());
input = game.readUserInput();
}
//game.update();
//client.close();
}catch(IOException e)
{
e.printStackTrace();
}
//}
}
}
Server class and ClientThread subclass
import java.net.*;
import java.util.Random;
import java.io.*;
public class Server implements IGameLogic
{
private ServerSocket serverSocket;
private Map map = null;
private int[] playerPosition;
private int collectedGold;
private boolean active;
public Server(int port) throws IOException
{
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(10000);
}
public void startServer()
{
map = new Map();
setMap(new File("example_map.txt"));
System.out.println("Game Started - Map Initialized");
while(true)
{
try
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
ClientThread ct = new ClientThread(server, this );
ct.start();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public void setMap(File file) {
map.readMap(file);
playerPosition = initiatePlayer();
active = true;
}
/**
* Prints how much gold is still required to win!
*/
public synchronized String hello() {
return "GOLD: " + (map.getWin() - collectedGold);
}
/**
* By proving a character direction from the set of {N,S,E,W} the gamelogic
* checks if this location can be visited by the player.
* If it is true, the player is moved to the new location.
* #return If the move was executed Success is returned. If the move could not execute Fail is returned.
*/
public synchronized String move(char direction) {
int[] newPosition = playerPosition.clone();
switch (direction){
case 'N':
newPosition[0] -=1;
break;
case 'E':
newPosition[1] +=1;
break;
case 'S':
newPosition[0] +=1;
break;
case 'W':
newPosition[1] -=1;
break;
default:
break;
}
if(map.lookAtTile(newPosition[0], newPosition[1]) != '#'){
playerPosition = newPosition;
if (checkWin())
quitGame();
return "SUCCESS";
} else {
return "FAIL";
}
}
public synchronized String pickup() {
if (map.lookAtTile(playerPosition[0], playerPosition[1]) == 'G') {
collectedGold++;
map.replaceTile(playerPosition[0], playerPosition[1], '.');
return "SUCCESS, GOLD COINS: " + collectedGold;
}
return "FAIL" + "\n" + "There is nothing to pick up...";
}
/**
* The method shows the dungeon around the player location
*/
public synchronized String look() {
String output = "";
char [][] lookReply = map.lookWindow(playerPosition[0], playerPosition[1], 5);
lookReply[2][2] = 'P';
for (int i=0;i<lookReply.length;i++){
for (int j=0;j<lookReply[0].length;j++){
output += lookReply[j][i];
}
output += "\n";
}
return output;
}
public boolean gameRunning(){
return active;
}
/**
* Quits the game when called
*/
public void quitGame() {
System.out.println("The game will now exit");
active = false;
}
/**
* finds a random position for the player in the map.
* #return Return null; if no position is found or a position vector [y,x]
*/
private int[] initiatePlayer() {
int[] pos = new int[2];
Random rand = new Random();
pos[0]=rand.nextInt(map.getMapHeight());
pos[1]=rand.nextInt(map.getMapWidth());
int counter = 1;
while (map.lookAtTile(pos[0], pos[1]) == '#' && counter < map.getMapHeight() * map.getMapWidth()) {
pos[1]= (int) ( counter * Math.cos(counter));
pos[0]=(int) ( counter * Math.sin(counter));
counter++;
}
return (map.lookAtTile(pos[0], pos[1]) == '#') ? null : pos;
}
/**
* checks if the player collected all GOLD and is on the exit tile
* #return True if all conditions are met, false otherwise
*/
protected boolean checkWin() {
if (collectedGold >= map.getWin() &&
map.lookAtTile(playerPosition[0], playerPosition[1]) == 'E') {
System.out.println("Congratulations!!! \n You have escaped the Dungeon of Dooom!!!!!! \n"
+ "Thank you for playing!");
return true;
}
return false;
}
public static void main(String [] args)
{
//int port = Integer.parseInt(args[0]);
int port = 40004;
try
{
//Thread t = new Server(port);
//t.start();
Server s = new Server(port);
s.startServer();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
class ClientThread extends Thread {
//private byte[] data = new byte[255];
//private Socket socket;
private Socket _socket;
private Server _server;
public ClientThread(Socket socket, Server s) {
// for (int i = 0; i < data.length; i++)
// data[i] = (byte) i;
this._socket = socket;
this._server = s;
}
public void run() {
/* try {
OutputStream out = new BufferedOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
out.write(data);
}
socket.close();
} catch (Exception e) {
} */
try{
System.out.println("Just connected to " + _socket.getRemoteSocketAddress());
while ( _server.gameRunning() ) {
DataInputStream in = new DataInputStream(_socket.getInputStream());
// System.out.println(in.readUTF());
String input = in.readUTF();
System.out.println("Received from client: " + input );
DataOutputStream out = new DataOutputStream(_socket.getOutputStream());
//out.("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
if ( input.equals("LOOK") ) {
//String output = look();
System.out.println("LOOK" );
out.writeUTF( _server.look() );
} else if ( input.equals("HELLO") ) {
System.out.println("HELLO");
out.writeUTF( _server.hello() );
} else if ( input.equals("PICKUP") ) {
System.out.println("PICKUP");
out.writeUTF( _server.pickup() );
} else if ( input.equals("QUIT") ) {
System.out.println("QUIT");
_server.quitGame();
out.writeUTF( "The game has completed" );
} else if ( input.equals("MOVE N") ) {
System.out.println("MOVE N");
out.writeUTF( _server.move('N') );
} else if ( input.equals("MOVE E") ) {
System.out.println("MOVE E");
out.writeUTF( _server.move('E') );
} else if ( input.equals("MOVE S") ) {
System.out.println("MOVE S");
out.writeUTF( _server.move('S') );
} else if ( input.equals("MOVE W") ) {
System.out.println("MOVE W");
out.writeUTF( _server.move('W') );
} else {
out.writeUTF("Invalid Command");
}
}
}catch(IOException e){
//ioex.printStackTrace();
e.printStackTrace();
//break;
}
//DataOutputStream out = new DataOutputStream(server.getOutputStream());
//out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
//server.close();
}
}