Android client/server application - proper way to receive messages continously - java

I'm trying to make a client/server application using an Android phone as a client using AsyncTask to send messages from UI.
I've written some very basic implementation just to test the connection and the way that messages are received / sent and I found a very big problem.
The client part seems to work fine..from my perspective. But the server part is the problem. I can't make the server reading and displaying messages countinously from the client.
I tried something like while(line = (in.readLine()) != null) {} but it doesn't seems to work.
After I sent my first word from the client, the server reads null and it stops.
Can someone show me a proper way to keep the server running while the client is not sending nothing?
I'd like to avoid using while(true) if it's not 100% necessary.
Here is the implementation until now:
Server:
public class SocketServerThread extends Thread {
private static final Logger log = Logger.getLogger(SocketServerThread.class);
private static final int SERVER_PORT_NUMBER = 5000;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT_NUMBER);
serverSocket.setReuseAddress(true);
log.info("Waiting for connection...");
Socket clientSocket = serverSocket.accept();
log.info("Connected! Receiving message...");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
} finally {
in.close();
clientSocket.close();
serverSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Client:
public class MyAsyncTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "MyAsyncTask";
private static final String SERVER_IP_ADDRESS = "10.0.2.2";
private static final int SERVER_PORT_NUMBER = 5000;
private PrintWriter out;
#Override
protected String doInBackground(String... params) {
String message = "";
try {
InetAddress address = InetAddress.getByName(SERVER_IP_ADDRESS);
Log.d(TAG, "Connecting...");
Socket socket = new Socket(address, SERVER_PORT_NUMBER);
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.d(TAG, "I/O created");
message = params[0];
if (!message.equals("stop")) {
sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
private void sendMessage(String message) {
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
Log.d(TAG, "Sent message: " + message);
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute(), s: " + s);
}
Thank you.

The problem is that your BufferedReader only read the first input stream. In order to receive the text after that, you have to re-read the input stream. I do it by recreating the socket when I am done reading, so that I can read next coming data. I am using the following code in my app. You can use this
private ServerSocket serverSocket;
public static final int SERVERPORT = 5000;
Thread serverThread = null;
public void startSocketServer(){
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
public void stopSocket(){
if(serverSocket != null){
try{
serverSocket.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
Log.wtf(TAG,"Socket: New Socket");
serverSocket = new ServerSocket(SERVERPORT);
if(serverSocket == null){
runOnUiThread(new Runnable() {
#Override
public void run() {
startSocketServer();
}
});
return;
}
while (!Thread.currentThread().isInterrupted() && !serverSocket.isClosed()) {
try {
socket = serverSocket.accept();
Log.wtf(TAG,"Socket: Accepting");
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
Log.wtf(TAG,"Socket: Error");
e.printStackTrace();
}
if(Thread.currentThread().isInterrupted()){
Log.wtf(TAG, "Thread Interrupted");
}
if(serverSocket.isClosed()){
Log.wtf(TAG, "serverSocket closed");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
log.info("Connected! Receiving message...");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
try {
while (true) {
String line = in.readLine();
if (line != null) {
log.info(line);
}
else
break;//This will exit the loop and refresh the socket for next data
}
} catch (Exception e) {
log.error("Unexpected exception while sending / receiving messages.");
e.printStackTrace();
}
finally {
in.close();
clientSocket.close();
}
refreshSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void refreshSocket(){
runOnUiThread(new Runnable() {
#Override
public void run() {
stopSocket();
startSocketServer();
}
});
}
Just call startSocketServer() to start the server socket in your code.

Related

TCP Android Server and C# Client

I am trying to create an Android Server and Client on C# base on TCP Socket. I want them both to send and received a string(Data) so I can make a command base on the given string(Data). For the meantime, the Server can listen to incoming clients and the Clients can connect to Server. But I have two problem and i can't solve it.
PROBLEMS:
1. When i try to send the data to Server, the Server was unable to Read it.
2. When the Client is Disconnected, the Server is giving me a loop of Null.
I already try to Search about communicating C# and Android using TCP but i didn't found anything like what i need.
The following code is for Android Server.
I am having a loop of Null in class CommunicationThread when the client is Disconnected. I think it's because I am using a while for reading the Data from client, but since it become disconnected then it is resulting a null.
public class MainActivity extends AppCompatActivity {
TextView tx1, tx_waiting;
private ServerSocket serverSocket;
Handler updateConversationHandler, dg;
Thread serverThread = null;
public static final int SERVERPORT = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx1 = (TextView)findViewById(R.id.textView1);
tx_waiting = (TextView)findViewById(R.id.tx_waiting);
//Start the Server
try{
updateConversationHandler = new Handler();
dg = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tx_waiting.setVisibility(View.VISIBLE);
Log.d("Server Starting","Server Already Started.");
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
Log.d("Server Stop","Successfully Stopped the Server Without any Error.");
} catch (IOException e) {
Log.e("Server Failed to Stop",e.toString());
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
Log.d("Server Thread","Server Thread Already Started.");
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
Log.d("Server Socket","New Client is Connected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
Log.d("Input Stream","Input Stream Received!.");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
Log.d("Update Convers.","Conversation was Updating...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
Log.d("Client Data",msg.toString());
}
}
}
The following code is for C# Client to Connect and Send the Data.
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
Task f = Task.Factory.StartNew(() => {
//Connect the Client into Server
try {
clientSocket.Connect(tb_ip.Text, int.Parse(tb_port.Text));
}
catch (Exception ezz) {
MessageBox.Show("Server Not Found.");
}
//Assuming that the CLient is Connected then Send a Sample Data
try {
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("This is Sample Data");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
catch (Exception er) {
Console.WriteLine(er.ToString());
}
});
I have no method yet for Sending the Data from Server to Client since I am just starting to make this thing works, But if you have anything that can help me about this then i will really appreciate it. Thanks.

Java Sockets sending multiple objects to the same server

I'm trying to send multiple Objects through a socket to a java server.
To have a gerneral type I convert my messages into an instance of the class Message and send this object to the server.
I wrote a little testclass, which sends three objects to the server.
The problem is, only one objects reaches the server.
I tried nearly everything, without success.
My Server:
public class Server {
private ServerConfig conf = new ServerConfig();
private int port = Integer.parseInt(conf.loadProp("ServerPort"));
Logger log = new Logger();
ServerSocket socket;
Chat chat = new Chat();
public static void main(String[] args) {
Server s = new Server();
if (s.runServer()) {
s.listenToClients();
}
}
public boolean runServer() {
try {
socket = new ServerSocket(port);
logToConsole("Server wurde gestartet!");
return true;
} catch (IOException e) {
logToConsole("Server konnte nicht gestartet werden!");
e.printStackTrace();
return false;
}
}
public void listenToClients() {
while (true) {
try {
Socket client = socket.accept();
ObjectOutputStream writer = new ObjectOutputStream(client.getOutputStream());
Thread clientThread = new Thread(new Handler(client, writer));
clientThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void logToConsole(String message) {
System.out.print(message);
}
public class Handler implements Runnable {
Socket client;
ObjectInputStream reader;
ObjectOutputStream writer;
User user;
public Handler(Socket client, ObjectOutputStream writer) {
try {
this.client = client;
this.writer = writer;
this.reader = new ObjectInputStream(client.getInputStream());
this.user = new User();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
Message incomming;
try {
while ((incomming = (Message) reader.readUnshared()) != null) {
logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n");
logToConsole(
"Vom Client: \n" + incomming.getType() + "-----" + incomming.getValue().toString());
handle(incomming);
}
} catch (SocketException se) {
se.printStackTrace();
Thread.currentThread().interrupt();
} catch (IOException ioe) {
ioe.printStackTrace();
Thread.currentThread().interrupt();
} catch (ClassNotFoundException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
private void handle(Message m) throws IOException {
String type = m.getType();
if (type.equals(config.ConstantList.Network.CHAT.toString())) {
chat.sendMessage(m);
} else if (type.equals(config.ConstantList.Network.LOGIN.toString())) {
System.out.println(user.login(m.getValue().get(0), writer));
System.out.println(m.getValue().get(0));
}
}
}
}
The Client:
public class Connect {
Socket client = null;
ObjectOutputStream writer = null;
ObjectInputStream reader = null;
private Config conf = new Config();
//private String host = conf.loadProp("ServerIP");
String host = "localhost";
private int port = Integer.parseInt(conf.loadProp("ServerPort"));
public boolean connectToServer() {
try {
client = new Socket(host, port);
reader = new ObjectInputStream(client.getInputStream());
writer = new ObjectOutputStream(client.getOutputStream());
logMessages("Netzwerkverbindung hergestellt");
Thread t = new Thread(new MessagesFromServerListener());
t.start();
return true;
} catch (Exception e) {
logMessages("Netzwerkverbindung konnte nicht hergestellt werden");
e.printStackTrace();
return false;
}
}
public boolean isConnectionActive() {
if (client == null || writer == null || reader == null){
return false;
}else{
return true;
}
}
public void sendToServer(Message m) {
try {
writer.reset();
writer.writeUnshared(m);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
And I try to send the objects with the class:
public void sendChatMessage(String username, String message) throws InterruptedException {
ChatMessage cm = new ChatMessage();
cm.setChat(username, null, message);
Message m = new Message(cm);
conn.sendToServer(m);
System.out.println("SENDED");
}
public static void main(String[] args) throws InterruptedException {
String username = "testuser";
String chatmessage = "Hallo Welt!";
connect.connect();
sendChatMessage(username, chatmessage);
sendChatMessage(username, chatmessage);
sendChatMessage(username, chatmessage);
}
I know that this is always the same message, but it is only for test purposes.
The messages are the objects they are Serializable and with only one object it works as designed.
Does anyone can see where I made my mistake?
while ((incomming = (Message) reader.readUnshared()) != null) {
Here you are reading an object, and blocking until it arrives.
logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n");
Here you are reading another object, and blocking till it arrives, and then erroneously logging it as the object you already read in the previous line.
Instead of logging reader.readObject(), you should be logging the value of incoming, which you have also misspelt.
And the loop is incorrect. readObject() doesn't return null at end of stream: it throws EOFException. It can return null any time you write null, so using it as a loop termination condition is completely wrong. You should catch EOFException and break.
Found the solution, the line logToConsole("Vom Client: \n" + reader.readObject().toString() + "\n"); in the Server class, blocks the connection.

Keep communication open between server and client - Java

How do you make a client which is able to send a server multiple messages at anytime, and therefore a server listening for a message all the time.
Right now I have wrote some code which only allows me to send a message once. I thought this was due to me closing the input/output streams and the sockets. So I have been playing around for a while now and I can't seem to do it!
Client:
public class Client {
private Socket socket;
private OutputStream os;
public Client() {}
public void connectToServer(String host, int port) {
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
sendMessage();
}
public void sendMessage() {
try {
os = socket.getOutputStream();
String string = "Anthony";
byte[] b = string.getBytes(Charset.forName("UTF-8"));
os.write(b);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void STOP() {
stopOutput();
stopServer();
}
public void stopServer() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopOutput() {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
public class ConnectionHandler implements Runnable {
private Socket clientSocket;
private BufferedReader in;
public ConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
String clientAddress = clientSocket.getInetAddress().toString()
.substring(1);
System.out.println("Connected to " + clientAddress);
try {
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while ((inputLine = in.readLine()) != null) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void STOP() {
stopInput();
stopConnection();
}
public void stopInput() {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopConnection() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the moment on the client side, I send a message as soon as the socket is opened but after when I call the send function from another class it does not send...
How should I do this? Or what am I doing wrong?
Thanks in advance.
p.s. I am guessing client-server is the same as server-client, so if I know how to do one way I can easily switch it around... right?
Turns outs it was a simple error.
I as writing (sending-client) as an OutputStream however I was then reading (receiving-server) as BufferedReader! ha
So quick tip for anyone, make sure you receive messages the same way you send them!
Thanks for everyone who tried helping.
Your server is accepting data all the time, so you just have to save the OutputStream of you Client somewhere and write data to it every now and then. But do not close it, because then you close the Client socket, too.
After you have done that, you would need to change something else, because now your call of in.readLine() blocks your server, because it waits for the client to send something. To prevent that, you could try to add sending a String like "close" to the server when you want to close your client, something like that:
public void STOP() {
os.write("close".getBytes(Charset.forName("UTF-8")));
stopOutput();
stopServer();
}
and change the code in your server to
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while (!(inputLine = in.readLine()).equals("close")) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}

How to stop all instances of a thread

I'm developping a socket-based game in Java about riddles in a competitive way.
The server program creates a response thread besides other threads for each player (client), what I want to do is stop (or interrupt) all those response threads once a player sends the right response.
Here's my code
public class testReponse implements Runnable {
private Socket socket;
BufferedReader in;
PrintWriter out;
String reponse="";
public testReponse(Socket socket2){
socket = socket2;
}
#Override
public void run() {
while(!reponse.equals("right")){
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String reponse = in.readLine();
System.out.println("Reponse : "+ reponse);
if(reponse.equals("right")){
out.println("correct");
out.flush();
} else {
out.println("incorrect");
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is not clear where is your server code is. However, the way I would do it is by having an AtomicBoolean as an instance variable in the server code. Once the "right" message is received from any of the clients, the value would change to false. In the code in the server side if you see that the value is false, then you stop!
This is one way to go about it but there might be better ways to do it though.
public class MyServer {
private AtomicBoolean keepServerOn = new AtomicBoolean(true);
public void setKeepServerOff() {
keepServerOn.set(false);
}
public void shouldKeepGoing() {
return keepServerOn.get();
}
public static void main(Strings[] args) {
....// where you accept clients and create TestResponse
MyServer myServer = new MyServer();
...// somewhere new TestResponse(socket, myServer);
}
}
public class testReponse implements Runnable {
private MyServer server;
private Socket socket;
private AtomicBoolean keepServerOn = new AtomicBoolean(true);
public testReponse(Socket socket2, MyServer server){
socket = socket2;
}
#Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
while(server.shouldKeepGoing()){
String reponse = in.readLine();
System.out.println("Reponse : "+ reponse);
if(reponse.equals("right")){
server.setKeepServerOff();
out.println("correct");
out.flush();
} else {
out.println("incorrect");
out.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!= null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Java Client Server - Multiple Event Handling for the Client

I'm trying to setup a client server application using socket programming. My client connects to the server, but I'm unable to get the multiple event handling to work. My client applet has two text boxes and buttons associated with each one of of them. When I click button one, I was trying to get "Hello" to be displayed in the text box. When I click on button two, I was trying to get "Hello there" to be displayed in the second text box. However, only one value (the value I first click) shows up in both of the text boxes. Is my event handling mechanism incorrect? I am implementing the serializable interface and the client server communication deals with objects. Can someone please tell me what the problem in the code is? I haven't posted the ObjectCommunication.java code, but it simply implements the serializable interface and has the getter and setter (takes a string as an input parameter) method.
Many thanks!
The following is my server code:
import java.io.*;
import java.net.*;
public class Server_App {
public static void main(String[] args) {
try {
ServerSocket holder = new ServerSocket(4500);
for (;;) {
Socket incoming = holder.accept();
new ServerThread(incoming).start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ServerThread extends Thread
{
public ServerThread(Socket i) {
incoming = i;
}
public void run() {
try {
ObjectCommunication hold = new ObjectCommunication();
ObjectInputStream input = new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(incoming.getOutputStream());
hold = (ObjectCommunication) input.readObject();
if ((hold.getMessage()).equals("Event 1")) {
System.out.println("Message read: " + hold.getMessage());
hold.setMessage("Hello!");
} else if ((hold.getMessage()).equals("Event 2")) {
System.out.println("Message read:" + hold.getMessage());
hold.setMessage("Hello there!");
}
output.writeObject(hold);
input.close();
output.close();
incoming.close();
} catch (Exception e) {
System.out.println(e);
}
}
ObjectCommunication hold = null;
private Socket incoming;
}
The following is the client code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client_App extends Applet {
TextField textVal;
TextField anotherTextVal;
Socket socket;
ObjectCommunication hold = new ObjectCommunication();
ObjectCommunication temp = new ObjectCommunication();
ObjectOutputStream OutputStream;
ObjectInputStream InputStream;
public void init() {
socketConnection();
createGUI();
validate();
}
public void socketConnection() {
try {
socket = new Socket("127.0.0.1", 4500);
} catch (Exception e) {
System.out.println("Unknown Host");
}
try {
OutputStream = new ObjectOutputStream(socket.getOutputStream());
InputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
System.out.println("Error: " + ex);
return;
}
}
public void createGUI() {
Button button = new Button("Hello Button");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button_actionPerformed(evt);
}
});
textVal = new TextField(6);
add(textVal);
Button anotherButton = new Button("Hello there Button");
add(anotherButton);
anotherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
anotherButton_actionPerformed(evt);
}
});
anotherTextVal = new TextField(6);
add(anotherTextVal);
}
public void button_actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof Button)
if (actionCommand.equals("Hello Button")) {
try {
temp.setMessage("Event 1");
//OutputStream.writeObject(temp);
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
textVal.setText(hold.getMessage());
}
}
public void anotherButton_actionPerformed(ActionEvent evt) {
String action_Command = evt.getActionCommand();
if (evt.getSource() instanceof Button)
if (action_Command.equals("Hello there Button")) {
try {
temp.setMessage("Event 2");
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
anotherTextVal.setText(hold.getMessage());
}
}
class ListenToServer extends Thread {
public void run() {
while (true) {
try {
hold = (ObjectCommunication) InputStream.readObject();
} catch (IOException e) {} catch (ClassNotFoundException e2) {}
}
}
}
class SendToServer extends Thread {
public void run() {
while (true) {
try {
OutputStream.writeObject(temp);
} catch (IOException e) {}
}
}
}
}
To be honest - I'm a little bit lazy to read through your code and seek there for a bug :) Nevertheless I'll post you here my snippet for socket-based multiple client-server application..
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
Hope this helps :] If anything would be ununderstandable, don't hesitate to ask for more details :)

Categories

Resources