Java socket exchange message between client and server
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I have trouble in Java socket multithread while I learn by myself about socket on Oracle's Java page, after reading the example about TCP and UDP socket.
I try to use this knowledge to write something to exchange messages between client and server.
But, I wonder when client send message to server with multithread, and server has some condition.
Example: When client send to server a letter A
Server will receive and has a condition like
if(inputfromClient.equals("A")){
// how to make input fromClient is null after get message (inputstream) from client?
}
In the comment of code snippet above, you can see my question, because after client sends input that is A, then client will send next letter like B, in a structure like this:
if(inputfromClient.equals("A")){
if(inputfromClient.equals("B")){
//some condition
}
}
my server code is like:
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
String intputLine, outputLine;
public TCPServerThread(Socket socket){
client = socket;
}
public void run(){
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
gameHandle g = new gameHandle();
boolean condition = true;
while((intputLine=in.readLine()) != null){
outputLine = g.processInput(intputLine);
out.println(outputLine);
System.out.println(outputLine);
}
out.close();
in.close();
client.close();
} catch (IOException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my client code:
public class ClientTCP {
public static void main(String args) {
try {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
//System.out.println(in.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Thank you very much.
Edited
Ok to make sense as i mention before
Client send messages to server
Client: onePMode
client: internet
....
and server get messages from client and compare it
if(inputLine.equals("onePMode")){
// it will continue to compare inputline is satisfy with sub condition
if(inputLine.equals("internet"){
//do something
}
}
Edited
GameHandle To Handle Input
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.net.Socket;
import java.util.Random;
/**
*
* @author ***
*/
public class gameHandle {
private String modePlay = "";
private String wait = "wait";
private String status = wait;
private String keyword = "";
private Socket client;
private String letter = "";
private String onePMode ="onePMode";
private String getWord = "getWord";
private String twoPMode = "twoPMode";
private String waitForPlayer = "waitforPlayer";
private String ready = "ready";
private String question = "question";
public gameHandle(){}
public gameHandle(Socket socket,String Mode, String keyword, String letter){
client = socket;
this.keyword = keyword;
this.letter = letter;
modePlay = Mode;
}
//array with word will be rando,
String words = {"laptop", "network", "device", "game", "mobile",
"word", "november", "december", "signal", "internet","localhost","boot", "socket",
"client", "server", " port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
"computer", "microsoft", "lan"};
//this method get random word from array
public String getWord(){
Random r = new Random();
String randomString = words[r.nextInt(words.length)];
return randomString;
}
public String processInput(String inputString){
String outPut = "";
if(status.equals("wait")){
if(inputString.equals(onePMode)){
status = question;
outPut = "hello";
// outPut = question;
}
}else if(status.equals(question)){
if(inputString.equals(getWord)){
/*keyword = getWord();
outPut = getWord();
System.out.println(keyword);
status = question;*/
outPut = "getworrdddrdd";
System.out.println("get worddddddddd");
}else if(keyword.contains(inputString)){
System.out.println("containt");
}
}
return outPut;
}
public static void main(String args) {
gameHandle a = new gameHandle();
System.out.println(a.getWord());
}
}
java sockets
|
show 2 more comments
I have trouble in Java socket multithread while I learn by myself about socket on Oracle's Java page, after reading the example about TCP and UDP socket.
I try to use this knowledge to write something to exchange messages between client and server.
But, I wonder when client send message to server with multithread, and server has some condition.
Example: When client send to server a letter A
Server will receive and has a condition like
if(inputfromClient.equals("A")){
// how to make input fromClient is null after get message (inputstream) from client?
}
In the comment of code snippet above, you can see my question, because after client sends input that is A, then client will send next letter like B, in a structure like this:
if(inputfromClient.equals("A")){
if(inputfromClient.equals("B")){
//some condition
}
}
my server code is like:
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
String intputLine, outputLine;
public TCPServerThread(Socket socket){
client = socket;
}
public void run(){
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
gameHandle g = new gameHandle();
boolean condition = true;
while((intputLine=in.readLine()) != null){
outputLine = g.processInput(intputLine);
out.println(outputLine);
System.out.println(outputLine);
}
out.close();
in.close();
client.close();
} catch (IOException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my client code:
public class ClientTCP {
public static void main(String args) {
try {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
//System.out.println(in.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Thank you very much.
Edited
Ok to make sense as i mention before
Client send messages to server
Client: onePMode
client: internet
....
and server get messages from client and compare it
if(inputLine.equals("onePMode")){
// it will continue to compare inputline is satisfy with sub condition
if(inputLine.equals("internet"){
//do something
}
}
Edited
GameHandle To Handle Input
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.net.Socket;
import java.util.Random;
/**
*
* @author ***
*/
public class gameHandle {
private String modePlay = "";
private String wait = "wait";
private String status = wait;
private String keyword = "";
private Socket client;
private String letter = "";
private String onePMode ="onePMode";
private String getWord = "getWord";
private String twoPMode = "twoPMode";
private String waitForPlayer = "waitforPlayer";
private String ready = "ready";
private String question = "question";
public gameHandle(){}
public gameHandle(Socket socket,String Mode, String keyword, String letter){
client = socket;
this.keyword = keyword;
this.letter = letter;
modePlay = Mode;
}
//array with word will be rando,
String words = {"laptop", "network", "device", "game", "mobile",
"word", "november", "december", "signal", "internet","localhost","boot", "socket",
"client", "server", " port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
"computer", "microsoft", "lan"};
//this method get random word from array
public String getWord(){
Random r = new Random();
String randomString = words[r.nextInt(words.length)];
return randomString;
}
public String processInput(String inputString){
String outPut = "";
if(status.equals("wait")){
if(inputString.equals(onePMode)){
status = question;
outPut = "hello";
// outPut = question;
}
}else if(status.equals(question)){
if(inputString.equals(getWord)){
/*keyword = getWord();
outPut = getWord();
System.out.println(keyword);
status = question;*/
outPut = "getworrdddrdd";
System.out.println("get worddddddddd");
}else if(keyword.contains(inputString)){
System.out.println("containt");
}
}
return outPut;
}
public static void main(String args) {
gameHandle a = new gameHandle();
System.out.println(a.getWord());
}
}
java sockets
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variableinputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside
– MYE
Feb 25 '12 at 16:30
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29
|
show 2 more comments
I have trouble in Java socket multithread while I learn by myself about socket on Oracle's Java page, after reading the example about TCP and UDP socket.
I try to use this knowledge to write something to exchange messages between client and server.
But, I wonder when client send message to server with multithread, and server has some condition.
Example: When client send to server a letter A
Server will receive and has a condition like
if(inputfromClient.equals("A")){
// how to make input fromClient is null after get message (inputstream) from client?
}
In the comment of code snippet above, you can see my question, because after client sends input that is A, then client will send next letter like B, in a structure like this:
if(inputfromClient.equals("A")){
if(inputfromClient.equals("B")){
//some condition
}
}
my server code is like:
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
String intputLine, outputLine;
public TCPServerThread(Socket socket){
client = socket;
}
public void run(){
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
gameHandle g = new gameHandle();
boolean condition = true;
while((intputLine=in.readLine()) != null){
outputLine = g.processInput(intputLine);
out.println(outputLine);
System.out.println(outputLine);
}
out.close();
in.close();
client.close();
} catch (IOException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my client code:
public class ClientTCP {
public static void main(String args) {
try {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
//System.out.println(in.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Thank you very much.
Edited
Ok to make sense as i mention before
Client send messages to server
Client: onePMode
client: internet
....
and server get messages from client and compare it
if(inputLine.equals("onePMode")){
// it will continue to compare inputline is satisfy with sub condition
if(inputLine.equals("internet"){
//do something
}
}
Edited
GameHandle To Handle Input
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.net.Socket;
import java.util.Random;
/**
*
* @author ***
*/
public class gameHandle {
private String modePlay = "";
private String wait = "wait";
private String status = wait;
private String keyword = "";
private Socket client;
private String letter = "";
private String onePMode ="onePMode";
private String getWord = "getWord";
private String twoPMode = "twoPMode";
private String waitForPlayer = "waitforPlayer";
private String ready = "ready";
private String question = "question";
public gameHandle(){}
public gameHandle(Socket socket,String Mode, String keyword, String letter){
client = socket;
this.keyword = keyword;
this.letter = letter;
modePlay = Mode;
}
//array with word will be rando,
String words = {"laptop", "network", "device", "game", "mobile",
"word", "november", "december", "signal", "internet","localhost","boot", "socket",
"client", "server", " port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
"computer", "microsoft", "lan"};
//this method get random word from array
public String getWord(){
Random r = new Random();
String randomString = words[r.nextInt(words.length)];
return randomString;
}
public String processInput(String inputString){
String outPut = "";
if(status.equals("wait")){
if(inputString.equals(onePMode)){
status = question;
outPut = "hello";
// outPut = question;
}
}else if(status.equals(question)){
if(inputString.equals(getWord)){
/*keyword = getWord();
outPut = getWord();
System.out.println(keyword);
status = question;*/
outPut = "getworrdddrdd";
System.out.println("get worddddddddd");
}else if(keyword.contains(inputString)){
System.out.println("containt");
}
}
return outPut;
}
public static void main(String args) {
gameHandle a = new gameHandle();
System.out.println(a.getWord());
}
}
java sockets
I have trouble in Java socket multithread while I learn by myself about socket on Oracle's Java page, after reading the example about TCP and UDP socket.
I try to use this knowledge to write something to exchange messages between client and server.
But, I wonder when client send message to server with multithread, and server has some condition.
Example: When client send to server a letter A
Server will receive and has a condition like
if(inputfromClient.equals("A")){
// how to make input fromClient is null after get message (inputstream) from client?
}
In the comment of code snippet above, you can see my question, because after client sends input that is A, then client will send next letter like B, in a structure like this:
if(inputfromClient.equals("A")){
if(inputfromClient.equals("B")){
//some condition
}
}
my server code is like:
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
String intputLine, outputLine;
public TCPServerThread(Socket socket){
client = socket;
}
public void run(){
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
gameHandle g = new gameHandle();
boolean condition = true;
while((intputLine=in.readLine()) != null){
outputLine = g.processInput(intputLine);
out.println(outputLine);
System.out.println(outputLine);
}
out.close();
in.close();
client.close();
} catch (IOException ex) {
Logger.getLogger(TCPServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my client code:
public class ClientTCP {
public static void main(String args) {
try {
Socket socket;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
//System.out.println(in.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ClientTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Thank you very much.
Edited
Ok to make sense as i mention before
Client send messages to server
Client: onePMode
client: internet
....
and server get messages from client and compare it
if(inputLine.equals("onePMode")){
// it will continue to compare inputline is satisfy with sub condition
if(inputLine.equals("internet"){
//do something
}
}
Edited
GameHandle To Handle Input
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.net.Socket;
import java.util.Random;
/**
*
* @author ***
*/
public class gameHandle {
private String modePlay = "";
private String wait = "wait";
private String status = wait;
private String keyword = "";
private Socket client;
private String letter = "";
private String onePMode ="onePMode";
private String getWord = "getWord";
private String twoPMode = "twoPMode";
private String waitForPlayer = "waitforPlayer";
private String ready = "ready";
private String question = "question";
public gameHandle(){}
public gameHandle(Socket socket,String Mode, String keyword, String letter){
client = socket;
this.keyword = keyword;
this.letter = letter;
modePlay = Mode;
}
//array with word will be rando,
String words = {"laptop", "network", "device", "game", "mobile",
"word", "november", "december", "signal", "internet","localhost","boot", "socket",
"client", "server", " port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
"computer", "microsoft", "lan"};
//this method get random word from array
public String getWord(){
Random r = new Random();
String randomString = words[r.nextInt(words.length)];
return randomString;
}
public String processInput(String inputString){
String outPut = "";
if(status.equals("wait")){
if(inputString.equals(onePMode)){
status = question;
outPut = "hello";
// outPut = question;
}
}else if(status.equals(question)){
if(inputString.equals(getWord)){
/*keyword = getWord();
outPut = getWord();
System.out.println(keyword);
status = question;*/
outPut = "getworrdddrdd";
System.out.println("get worddddddddd");
}else if(keyword.contains(inputString)){
System.out.println("containt");
}
}
return outPut;
}
public static void main(String args) {
gameHandle a = new gameHandle();
System.out.println(a.getWord());
}
}
java sockets
java sockets
edited Feb 27 '12 at 8:14
MYE
asked Feb 25 '12 at 15:46
MYEMYE
49572041
49572041
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variableinputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside
– MYE
Feb 25 '12 at 16:30
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29
|
show 2 more comments
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variableinputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside
– MYE
Feb 25 '12 at 16:30
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variable
inputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside– MYE
Feb 25 '12 at 16:30
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variable
inputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside– MYE
Feb 25 '12 at 16:30
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29
|
show 2 more comments
2 Answers
2
active
oldest
votes
This might be simplest possible solution to your problem.
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
public TCPServerThread(Socket socket){
client = socket;
}
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String intputLine, outputLine;
intputLine = in.readLine();
while (intputLine != null) {
if(intputLine.equals("close")){
break;
}
processResponse(intputLine);
intputLine = in.readLine();
}
out.close();
in.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void processResponse(String response) {
// reset the statusBuffer so that we can process new commands from
// client
if (response.equals("reset")) {
statusBuffer = new String();
System.out.println("reset");
} else {
statusBuffer = statusBuffer + "#" + response;
}
if (statusBuffer.equals("#onePMode")) {
System.out.println("#onePMode");
} else if (statusBuffer.equals("#onePMode#internet")) {
System.out.println("#onePMode#internet");
} else if (statusBuffer.equals("#onePMode#play")) {
System.out.println("#onePMode#play");
}
}
}
I also found one mistake in your client code. Corrected code is as follows
public class ClientTCP {
public static void main(String args) {
try {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 1000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
if(fromUser.equals("close")){
break;
}
fromUser = stdIn.readLine();
}
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I executed program on my end and it run successfully. Now you should not have any problem in it.
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while iswhile((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean
– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
|
show 4 more comments
I think what you want is to make a decision based on the previous state. Then all you need is an object-oriented state machine.
If client enters 'A'
from initial state, then server should expect 'B'
or 'C'
as next input. If client enters 'B'
while the server is in state 'A'
, then server should expect 'D' or 'E' as next input. If this is what you want you should use State Design Pattern.
Every state you have, should be represented by an Object.
First you need to create an
Interface
for state and derive your
states from it.Then you should create a wrapper class for encapsulating your states.
This wrapper class serves as a state machine. It should maintain a
reference to the "current" State object.
When client enters a character, it will be passed to the wrapper instance. Then wrapper will pass it to the current state object. Then current State
object will process that data and decides the next state of the machine. It will create a next State(Object) and update the "current" State reference of wrapper class. Then the next client input will be handled by that newly created State
object.
Here is an example
State Interface
public interface State {
void perform(GameHandler context, String data);
}
Wrapper Class
public class GameHandler {
State current_state; // holds the current state of the state machine
// Initial state should be passed to the constructor
public GameHandler(State current_state) {
this.current_state = current_state;
}
// Sets the next state of the state machine
// Called by State objects
public void setNextState(State mystate) {
this.current_state = mystate;
}
// Outside world will communicate with state machine using this method
public void processRequest(String data){
current_state.perform(this,data);
}
}
State Implementations
public class State_A implements State {
@Override
public void perform(GameHandler context, String data) {
/* Process input data.
* Based on your processing, decide the next state
* Then set that sate (assuming it as State_B)
*/
context.setNextState(new State_B());
}
}
public class State_B implements State {
@Override
public void perform(GameHandler context, String data) {
/* process input data.
* based on your processing, decide the next state
* then set that sate (assuming it as State_C)
*/
context.setNextState(new State_C());
}
}
How to use this in your server
...
// Assuming State_A as the initial state
GameHandler g = new GameHandler(new State_A());
boolean condition = true;
while((intputLine=in.readLine()) != null)
{
g.processRequest(intputLine);
}
...
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9445475%2fjava-socket-exchange-message-between-client-and-server%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
This might be simplest possible solution to your problem.
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
public TCPServerThread(Socket socket){
client = socket;
}
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String intputLine, outputLine;
intputLine = in.readLine();
while (intputLine != null) {
if(intputLine.equals("close")){
break;
}
processResponse(intputLine);
intputLine = in.readLine();
}
out.close();
in.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void processResponse(String response) {
// reset the statusBuffer so that we can process new commands from
// client
if (response.equals("reset")) {
statusBuffer = new String();
System.out.println("reset");
} else {
statusBuffer = statusBuffer + "#" + response;
}
if (statusBuffer.equals("#onePMode")) {
System.out.println("#onePMode");
} else if (statusBuffer.equals("#onePMode#internet")) {
System.out.println("#onePMode#internet");
} else if (statusBuffer.equals("#onePMode#play")) {
System.out.println("#onePMode#play");
}
}
}
I also found one mistake in your client code. Corrected code is as follows
public class ClientTCP {
public static void main(String args) {
try {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 1000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
if(fromUser.equals("close")){
break;
}
fromUser = stdIn.readLine();
}
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I executed program on my end and it run successfully. Now you should not have any problem in it.
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while iswhile((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean
– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
|
show 4 more comments
This might be simplest possible solution to your problem.
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
public TCPServerThread(Socket socket){
client = socket;
}
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String intputLine, outputLine;
intputLine = in.readLine();
while (intputLine != null) {
if(intputLine.equals("close")){
break;
}
processResponse(intputLine);
intputLine = in.readLine();
}
out.close();
in.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void processResponse(String response) {
// reset the statusBuffer so that we can process new commands from
// client
if (response.equals("reset")) {
statusBuffer = new String();
System.out.println("reset");
} else {
statusBuffer = statusBuffer + "#" + response;
}
if (statusBuffer.equals("#onePMode")) {
System.out.println("#onePMode");
} else if (statusBuffer.equals("#onePMode#internet")) {
System.out.println("#onePMode#internet");
} else if (statusBuffer.equals("#onePMode#play")) {
System.out.println("#onePMode#play");
}
}
}
I also found one mistake in your client code. Corrected code is as follows
public class ClientTCP {
public static void main(String args) {
try {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 1000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
if(fromUser.equals("close")){
break;
}
fromUser = stdIn.readLine();
}
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I executed program on my end and it run successfully. Now you should not have any problem in it.
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while iswhile((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean
– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
|
show 4 more comments
This might be simplest possible solution to your problem.
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
public TCPServerThread(Socket socket){
client = socket;
}
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String intputLine, outputLine;
intputLine = in.readLine();
while (intputLine != null) {
if(intputLine.equals("close")){
break;
}
processResponse(intputLine);
intputLine = in.readLine();
}
out.close();
in.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void processResponse(String response) {
// reset the statusBuffer so that we can process new commands from
// client
if (response.equals("reset")) {
statusBuffer = new String();
System.out.println("reset");
} else {
statusBuffer = statusBuffer + "#" + response;
}
if (statusBuffer.equals("#onePMode")) {
System.out.println("#onePMode");
} else if (statusBuffer.equals("#onePMode#internet")) {
System.out.println("#onePMode#internet");
} else if (statusBuffer.equals("#onePMode#play")) {
System.out.println("#onePMode#play");
}
}
}
I also found one mistake in your client code. Corrected code is as follows
public class ClientTCP {
public static void main(String args) {
try {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 1000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
if(fromUser.equals("close")){
break;
}
fromUser = stdIn.readLine();
}
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I executed program on my end and it run successfully. Now you should not have any problem in it.
This might be simplest possible solution to your problem.
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
public TCPServerThread(Socket socket){
client = socket;
}
public void run() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String intputLine, outputLine;
intputLine = in.readLine();
while (intputLine != null) {
if(intputLine.equals("close")){
break;
}
processResponse(intputLine);
intputLine = in.readLine();
}
out.close();
in.close();
client.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void processResponse(String response) {
// reset the statusBuffer so that we can process new commands from
// client
if (response.equals("reset")) {
statusBuffer = new String();
System.out.println("reset");
} else {
statusBuffer = statusBuffer + "#" + response;
}
if (statusBuffer.equals("#onePMode")) {
System.out.println("#onePMode");
} else if (statusBuffer.equals("#onePMode#internet")) {
System.out.println("#onePMode#internet");
} else if (statusBuffer.equals("#onePMode#play")) {
System.out.println("#onePMode#play");
}
}
}
I also found one mistake in your client code. Corrected code is as follows
public class ClientTCP {
public static void main(String args) {
try {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("localhost", 1000);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = stdIn.readLine();
while(fromUser!= null){
out.println(fromUser);
if(fromUser.equals("close")){
break;
}
fromUser = stdIn.readLine();
}
out.close();
in.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I executed program on my end and it run successfully. Now you should not have any problem in it.
edited Feb 26 '12 at 17:13
answered Feb 25 '12 at 16:49
JProgrammerJProgrammer
9551825
9551825
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while iswhile((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean
– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
|
show 4 more comments
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while iswhile((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean
– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
first of all thank you very much, but i confuse perform inside if condition, as i mention before, client Type A and B, two letters also get from BufferedReader, if client send message onePMode and inside condition if(starsBuffer.equals("onePMode")){ if(startsBuffer.equals("Play"). but starsbuffer still get value is onePMode, how can solve it?
– MYE
Feb 25 '12 at 17:52
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
Trust me I am trying to understand your reply but could not figure out what exactly you want to say. I assume that by 'startsBuffer' you mean 'statusBuffer'. statusBuffer will hold value "onePmode#play' because it is appending the inputLine that it received from client. Lets start from start. Program starts, client sends 'onePmode' to server. Then the value of statusBuffer will be 'onePmode'. After that client will send 'Play' then the value of statusBuffer will be 'onePmode#play'. So you have to perform operation inside if("onePMode#twoPMode") condition this equivalent to inside if condition.
– JProgrammer
Feb 25 '12 at 18:23
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited
– MYE
Feb 25 '12 at 18:33
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while is
while((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean– MYE
Feb 25 '12 at 18:43
yes this is what i mean and you can see my edited but i try to implement your code, my condition in while is
while((inputLine == in.readline()) != null)
and then starsbuffer will lopp and format of it like : onePMode#onePMode onePMode#onePMode onePMode#onePMode onePMode#onePMode it loop ultil when i destroy proccess by click x on netbean– MYE
Feb 25 '12 at 18:43
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
Sorry I wrote {intputLine = in.readLine();} line out side of loop it should be inside. I have corrected code. Now it should work.
– JProgrammer
Feb 25 '12 at 18:50
|
show 4 more comments
I think what you want is to make a decision based on the previous state. Then all you need is an object-oriented state machine.
If client enters 'A'
from initial state, then server should expect 'B'
or 'C'
as next input. If client enters 'B'
while the server is in state 'A'
, then server should expect 'D' or 'E' as next input. If this is what you want you should use State Design Pattern.
Every state you have, should be represented by an Object.
First you need to create an
Interface
for state and derive your
states from it.Then you should create a wrapper class for encapsulating your states.
This wrapper class serves as a state machine. It should maintain a
reference to the "current" State object.
When client enters a character, it will be passed to the wrapper instance. Then wrapper will pass it to the current state object. Then current State
object will process that data and decides the next state of the machine. It will create a next State(Object) and update the "current" State reference of wrapper class. Then the next client input will be handled by that newly created State
object.
Here is an example
State Interface
public interface State {
void perform(GameHandler context, String data);
}
Wrapper Class
public class GameHandler {
State current_state; // holds the current state of the state machine
// Initial state should be passed to the constructor
public GameHandler(State current_state) {
this.current_state = current_state;
}
// Sets the next state of the state machine
// Called by State objects
public void setNextState(State mystate) {
this.current_state = mystate;
}
// Outside world will communicate with state machine using this method
public void processRequest(String data){
current_state.perform(this,data);
}
}
State Implementations
public class State_A implements State {
@Override
public void perform(GameHandler context, String data) {
/* Process input data.
* Based on your processing, decide the next state
* Then set that sate (assuming it as State_B)
*/
context.setNextState(new State_B());
}
}
public class State_B implements State {
@Override
public void perform(GameHandler context, String data) {
/* process input data.
* based on your processing, decide the next state
* then set that sate (assuming it as State_C)
*/
context.setNextState(new State_C());
}
}
How to use this in your server
...
// Assuming State_A as the initial state
GameHandler g = new GameHandler(new State_A());
boolean condition = true;
while((intputLine=in.readLine()) != null)
{
g.processRequest(intputLine);
}
...
add a comment |
I think what you want is to make a decision based on the previous state. Then all you need is an object-oriented state machine.
If client enters 'A'
from initial state, then server should expect 'B'
or 'C'
as next input. If client enters 'B'
while the server is in state 'A'
, then server should expect 'D' or 'E' as next input. If this is what you want you should use State Design Pattern.
Every state you have, should be represented by an Object.
First you need to create an
Interface
for state and derive your
states from it.Then you should create a wrapper class for encapsulating your states.
This wrapper class serves as a state machine. It should maintain a
reference to the "current" State object.
When client enters a character, it will be passed to the wrapper instance. Then wrapper will pass it to the current state object. Then current State
object will process that data and decides the next state of the machine. It will create a next State(Object) and update the "current" State reference of wrapper class. Then the next client input will be handled by that newly created State
object.
Here is an example
State Interface
public interface State {
void perform(GameHandler context, String data);
}
Wrapper Class
public class GameHandler {
State current_state; // holds the current state of the state machine
// Initial state should be passed to the constructor
public GameHandler(State current_state) {
this.current_state = current_state;
}
// Sets the next state of the state machine
// Called by State objects
public void setNextState(State mystate) {
this.current_state = mystate;
}
// Outside world will communicate with state machine using this method
public void processRequest(String data){
current_state.perform(this,data);
}
}
State Implementations
public class State_A implements State {
@Override
public void perform(GameHandler context, String data) {
/* Process input data.
* Based on your processing, decide the next state
* Then set that sate (assuming it as State_B)
*/
context.setNextState(new State_B());
}
}
public class State_B implements State {
@Override
public void perform(GameHandler context, String data) {
/* process input data.
* based on your processing, decide the next state
* then set that sate (assuming it as State_C)
*/
context.setNextState(new State_C());
}
}
How to use this in your server
...
// Assuming State_A as the initial state
GameHandler g = new GameHandler(new State_A());
boolean condition = true;
while((intputLine=in.readLine()) != null)
{
g.processRequest(intputLine);
}
...
add a comment |
I think what you want is to make a decision based on the previous state. Then all you need is an object-oriented state machine.
If client enters 'A'
from initial state, then server should expect 'B'
or 'C'
as next input. If client enters 'B'
while the server is in state 'A'
, then server should expect 'D' or 'E' as next input. If this is what you want you should use State Design Pattern.
Every state you have, should be represented by an Object.
First you need to create an
Interface
for state and derive your
states from it.Then you should create a wrapper class for encapsulating your states.
This wrapper class serves as a state machine. It should maintain a
reference to the "current" State object.
When client enters a character, it will be passed to the wrapper instance. Then wrapper will pass it to the current state object. Then current State
object will process that data and decides the next state of the machine. It will create a next State(Object) and update the "current" State reference of wrapper class. Then the next client input will be handled by that newly created State
object.
Here is an example
State Interface
public interface State {
void perform(GameHandler context, String data);
}
Wrapper Class
public class GameHandler {
State current_state; // holds the current state of the state machine
// Initial state should be passed to the constructor
public GameHandler(State current_state) {
this.current_state = current_state;
}
// Sets the next state of the state machine
// Called by State objects
public void setNextState(State mystate) {
this.current_state = mystate;
}
// Outside world will communicate with state machine using this method
public void processRequest(String data){
current_state.perform(this,data);
}
}
State Implementations
public class State_A implements State {
@Override
public void perform(GameHandler context, String data) {
/* Process input data.
* Based on your processing, decide the next state
* Then set that sate (assuming it as State_B)
*/
context.setNextState(new State_B());
}
}
public class State_B implements State {
@Override
public void perform(GameHandler context, String data) {
/* process input data.
* based on your processing, decide the next state
* then set that sate (assuming it as State_C)
*/
context.setNextState(new State_C());
}
}
How to use this in your server
...
// Assuming State_A as the initial state
GameHandler g = new GameHandler(new State_A());
boolean condition = true;
while((intputLine=in.readLine()) != null)
{
g.processRequest(intputLine);
}
...
I think what you want is to make a decision based on the previous state. Then all you need is an object-oriented state machine.
If client enters 'A'
from initial state, then server should expect 'B'
or 'C'
as next input. If client enters 'B'
while the server is in state 'A'
, then server should expect 'D' or 'E' as next input. If this is what you want you should use State Design Pattern.
Every state you have, should be represented by an Object.
First you need to create an
Interface
for state and derive your
states from it.Then you should create a wrapper class for encapsulating your states.
This wrapper class serves as a state machine. It should maintain a
reference to the "current" State object.
When client enters a character, it will be passed to the wrapper instance. Then wrapper will pass it to the current state object. Then current State
object will process that data and decides the next state of the machine. It will create a next State(Object) and update the "current" State reference of wrapper class. Then the next client input will be handled by that newly created State
object.
Here is an example
State Interface
public interface State {
void perform(GameHandler context, String data);
}
Wrapper Class
public class GameHandler {
State current_state; // holds the current state of the state machine
// Initial state should be passed to the constructor
public GameHandler(State current_state) {
this.current_state = current_state;
}
// Sets the next state of the state machine
// Called by State objects
public void setNextState(State mystate) {
this.current_state = mystate;
}
// Outside world will communicate with state machine using this method
public void processRequest(String data){
current_state.perform(this,data);
}
}
State Implementations
public class State_A implements State {
@Override
public void perform(GameHandler context, String data) {
/* Process input data.
* Based on your processing, decide the next state
* Then set that sate (assuming it as State_B)
*/
context.setNextState(new State_B());
}
}
public class State_B implements State {
@Override
public void perform(GameHandler context, String data) {
/* process input data.
* based on your processing, decide the next state
* then set that sate (assuming it as State_C)
*/
context.setNextState(new State_C());
}
}
How to use this in your server
...
// Assuming State_A as the initial state
GameHandler g = new GameHandler(new State_A());
boolean condition = true;
while((intputLine=in.readLine()) != null)
{
g.processRequest(intputLine);
}
...
answered Dec 18 '15 at 10:14
TMtechTMtech
51438
51438
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9445475%2fjava-socket-exchange-message-between-client-and-server%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What is the meaning of comment exactly? can you elaborate? And I see that, at client end, you are writing in a loop, but at server end you are reading just one line. Is it something wrong here?
– JProgrammer
Feb 25 '12 at 15:58
@JProgrammer yes i use loop to client for send messages continuous to server but in server i need to have condition like when client send message onePMode if this condition true, server will do next condition inside a condition above
– MYE
Feb 25 '12 at 16:14
ok. can you elaborate more on question (the one which is mentioned in comment in code)
– JProgrammer
Feb 25 '12 at 16:18
it mean when client send message like "A" to server, BufferedReader store it and then i set inputLine to store value of message ("A") when client Type A, server get it and compare to condition, and server continue to do a sub condition inside a main condition, but it still store a letter A in variable
inputLine
i want when client type A, server get it compare and wait for client type B to do a sub condition inside– MYE
Feb 25 '12 at 16:30
"How to make input fromClient is null after get message (inputstream) from": If this is your question, it is meaningless. Unless you're asking how to write 'inputFromClient = null;', in which case it is trivial beyond belief. I cannot make head or tail of your comment immediately above.
– user207421
Jul 11 '14 at 0:29