So, I just learned how to make sockets and all that good stuff in Java, and so my first try got me a message from the client, and then the client crashing. What was supposed to happen was get a message from the client, if that message is equal to this, then send data back. However, the if function for if the message was correct wasn't firing, even though the message was correct.
Even when I remove the if function to check if the string was right or not, the program still freezes up. And by the way, my server is a console application, and my client is a SWT application.
Here's the server code with the removed if function:
try {
System.out.println("Waiting for a connection...");
// Start a server
ServerSocket server = new ServerSocket(3211);
// Listen for anyone at that port
Socket socket = server.accept();
System.out.println("The client has connected!");
// Get the data being sent in
DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
DataOutputStream ouputStream = new DataOutputStream(socket.getOutputStream());
// Turn that into UTF-8
String data = inputStream.readUTF();
System.out.println("Received " + data);
ouputStream.writeUTF("Great!");
System.out.println("Awesome!");
socket.close();
inputStream.close();
ouputStream.close;
server.close();
System.out.println("Socket closed\n-----------------------------");
}
catch(IOException e) {
System.out.println(e);
}
And the client (which is fired when a button gets pressed):
try {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnecting to the server...");
Socket socket = new Socket("192.168.1.206", 3211);
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnected to the server!");
DataInputStream input = new DataInputStream(System.in);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("sweet");
String data = input.readUTF();
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nSERVER: " + data);
input.close();
output.close();
socket.close();
}
catch (IOException er) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\n" + er);
}
As soon as I press the button to try and start the connection (with the server already running), the client instantly freezes. It doesn't even send any of the "connecting to server" kind of stuff.
Any idea what's going wrong, and how to fix this?
Your client is reading from System.in. It should be reading from the socket input stream.
NB You only need to close the outermost output stream of a socket. That flushes it if necessary and closes the input stream and the socket. You're presently not only closing more than necessary but also in the wrong order,
Your socket is unable to send data because you did not called .flush() method on your outputstream reference. Use this one and you don't have to write flush() and close() method explicitely on streams
Server Code
System.out.println("Waiting for a connection...");
// Start a server
try (ServerSocket server = new ServerSocket(3211)) {
// Listen for anyone at that port
try (Socket socket = server.accept()) {
System.out.println("The client has connected!");
// Get the data being sent in
try (DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()))) {
try (DataOutputStream ouputStream = new DataOutputStream(socket.getOutputStream())) {
// Turn that into UTF-8
String data = inputStream.readUTF();
System.out.println("Received " + data);
ouputStream.writeUTF("Great!");
System.out.println("Awesome!");
}
}
}
System.out.println("Socket closed\n-----------------------------");
} catch (IOException e) {
System.out.println(e);
}
Client Code
try {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnecting to the server...");
try (Socket socket = new Socket("127.0.0.1", 3211)) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nConnected to the server!");
try (DataInputStream input = new DataInputStream(socket.getInputStream())) {
try (DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
output.writeUTF("sweet");
}
String data = input.readUTF();
System.out.println(String.format("data received from server '%s':\n", data));
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\nSERVER: " + data);
}
}
} catch (IOException er) {
allMessagesTextBox.setText(allMessagesTextBox.getText() + "\n" + er);
}
Output on Server
Waiting for a connection...
The client has connected!
Received sweet
Awesome!
Socket closed
-----------------------------
Output on Client
data received from server 'Great!':
Now moving to problem in your code.
See the client side code you have written DataInputStream input = new DataInputStream(System.in); instead of DataInputStream input = new DataInputStream(socket.getInputStream())
which causes the failure in receiving message from server
Related
I am creating and testing a simple TCP server on an Android emulator.
I use a simple Java client program to try to connect to the server running on the emulator. I attempt to send a simple string like "hello world".
I think the connection between the client and server is successfully initialized; however, data is not routed to the Android device.
The server thread blocks at line clientSentence = inFromClient.readLine(); and the client thread blocks at String serverResponse = inFromServer.readLine();.
I have port forwarded local host port 6100 to AVD virtual port 7100 as per Google docs with ADB
adb -s emulator-5554 forward tcp:6100 tcp:7100
Here is Java class TCPTestClient
public class TCPTestClient
{
public static void main(String argv[]) throws Exception
{
String sentenceToServer = "hello server";
System.out.println("initializing socket");
Socket clientSocket = new Socket("127.0.0.1", 6100);
System.out.println("socket initialized");
System.out.println("getting output stream to server");
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("found output stream to server");
System.out.println("getting input stream from server");
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("found input stream from server");
System.out.println("writing sentence to server");
outToServer.writeBytes(sentenceToServer );
System.out.println("sentence written");
System.out.println("waiting for sentence response from server");
String serverResponse = inFromServer.readLine();
System.out.println("serverResponse = "+serverResponse);
System.out.println("socket closed");
clientSocket.close();
}
}
Here is Android app method initTcpTestServer()
private void initTcpTestServer()
{
Log.d("TAG", "initTcpTestServer()");
try
{
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(7100);
while ( true )
{
Log.d("TAG", "looking for socket");
Socket connectionSocket = welcomeSocket.accept();
Log.d("TAG", "socket accepted");
Log.d("TAG", "getting input stream");
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
Log.d("TAG", "input stream found");
Log.d("TAG", "getting output stream");
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
Log.d("TAG", "output stream found");
Log.d("TAG", "reading input stream");
clientSentence = inFromClient.readLine();
Log.d("TAG", "input stream read");
Log.d("TAG", "input = " + clientSentence);
Log.d("TAG", "writing output back to client");
outToClient.writeBytes(clientSentence);
Log.d("TAG", "output written back to client");
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
If I initialize the TCP server first I get output
initTcpTestServer()
looking for socket
After initializing the TCP server and then initializing the TCP client I get from the server
getting input stream
input stream found
getting output stream
output stream found
reading input stream
and from the client
initializing socket
socket initialized
getting output stream to server
found output stream to server
getting input stream from server
found input stream from server
writing sentence to server
sentence written
waiting for sentence response from server
so it appears that the socket is established, but the server blocks at line
clientSentence = inFromClient.readLine();
and the client blocks at
String serverResponse = inFromServer.readLine();
becuase the client has written the data, but the server has never received it, and the client is hanging waiting for the server's reponse.
Thank you Scary Wombat. Adding a "\n" at the end of the String resulted in a successful TCP message to the server. A TCP server can indeed be set up on an Android emulator by configuring port forwarding on the AVD virtual router with ADB. However, I have only testing this on local host.
I am writing Socket program , Here Client Sends a String through Stream , Server Process it and writes back to Client. My problem is, after Server process the String , it Writes back to Stream but in client It can't able to read the Stream its showing exception as Exception in while: java.net.SocketException: socket closed Here is my code,
Client ,
public void run() {
while (true) {
try {
// Open your connection to a server, at port 1231
s1 = new Socket("localhost", 1231);
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
InputStream in=s1.getInputStream();
DataInputStream dis=new DataInputStream(in);
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
dos.close();
System.out.println(dis.readUTF());//it is the String from Server after processing
dis.close();
} catch (IOException ex) {
// Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Exception in while: " + ex);
}
}
In Server
public void run()
{
while(true){
try {
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
String clientData=dis.readUTF();
//processing task String
dos.writeUTF("Bus Registered Successfully");
dos.flush();
}
}
Here I am not able to read Bus Registered Successfully at client side . How to Solve this.?
Well there are many things not right in your program. But first let me answer your question ... you are closing the socket just after writing the stream ... so server throws exception, just remove dos.close(); just after the dos.flush();. It will run fine.
Now back to the programming practices ...
1) Server should accept the connection in a while(true) loop and then make a new thread. So following statement should not be the part of run method.
System.out.println("Waiting for connect to client");
s1=serverSocket.accept();
s1In = s1.getInputStream();
dis = new DataInputStream(s1In);
out=s1.getOutputStream();
dos=new DataOutputStream(out);
2) There is no need of run method in client. Because Every new client will be a new program that has its own variables and socket.
A quick look shows me that the reason the socket is closed is because you used dos.close().
Closing a DataInputStream (or PrintStream, or any similiar stream) will close the underlying socket.
Just take out dos.close().
You can also move the dos.close() to the very end of the try block. As a general rule, don't close anything related to the socket until you're done with the socket.
I have the code below:
while (true)
{
lengthInput = instr.readByte();
// Other code
}
The thing is that I'm using a client to send information to the socket, but after it finishes I got EOF Exception and it brokes the thread, what I need is to manages this and dont stop the thread, because I need to send more information and be able to read it.
Thanks in advance for your help.
I guess the problem is related to your socket initialization. You probably need to check if your client socket indeed successfully create a socket and bind to a specified port. You may also check your client really send data to the outstream and flush to the server side. I have a small project on Android emulators with socket communication. Both my client and serve extends from Java Thread class. Maybe you can gain some idea seeing my code below.
The client side
try {
socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(remote_port));//note we must keep the addr#10.0.2.2
// write out
out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(out_msg);
out.flush();
// read in
in = new ObjectInputStream(socket.getInputStream());
socket.setSoTimeout(1000);
in_msg.set_message((Message)in.readObject());
// close all
out.close();
in.close();
socket.close();
return true;
}catch(InterruptedIOException E){}
The server side
while (true) {
try {
// read in message
Socket ClientSocket = serverSocket.accept();
Message out_msg = new Message();
// read in message
ObjectInputStream in = new ObjectInputStream(ClientSocket.getInputStream());
Message in_msg = (Message) in.readObject();
//Log.d(TAG, "recv" + " content:" + in_msg.msg2Str());
message_process(in_msg, out_msg);
// write out message
ObjectOutputStream out = new ObjectOutputStream(ClientSocket.getOutputStream());
out.writeObject(out_msg);
out.flush();
} catch(Exception E){}
}
I'm struggling here...
I'm trying to determine if data was successfully sent to the server through a TCP socket using the OutputStream object. For testing on emulator socket communications is loss after 30 sec. For write data OutputStream.write(); its doesn't throw an exception , and local server continuously running its not crashing, only tcp socket connection is loss after some time. All the methods in the socket class return as though the socket is active and working. Is there anything I'm doing wrong here? Is there any socket implementation or stream implementation I can use to get an exception or error when the stream/ socket doesn't actually send the data in the buffer? Also setting setSoTimeout() on the socket doesn't seem to do anything.
Please guide me...
Here is my code:
private void sendRec() {
int lstream;
int port = 1012;
byte[] byterecv = new byte[1040];
while (true) {
System.out.println("POOL-2");
synchronized (recSendThread) {
try {
recSendThread.wait(20);
} catch (InterruptedException e) {
}
}
if (stopcall == true) {
// break;
}
try {
// Provides a client-side TCP socket
Socket clientRec = new Socket();
// serverSocket = new ServerSocket(port);
// serverSocket.setSoTimeout(5000);
// Connects this socket to the given remote host address and
// port
clientRec.connect(new InetSocketAddress("192.168.1.36", port));
System.out.println("Just connected to "
+ clientRec.getRemoteSocketAddress());
System.out.println("SENTS Rec BEFORE");
// output streams that write data to the network
OutputStream outToServerRec = clientRec.getOutputStream();
DataOutputStream outStreamRec = new DataOutputStream(
outToServerRec);
outStreamRec.write(bData);
System.out.println("SENTS Rec AFTER");
// input streams that read data from network
InputStream inFromServerRec = clientRec.getInputStream();
// clientRec.setSoTimeout(5000);
DataInputStream inStreamRec = new DataInputStream(
inFromServerRec);
while ((lstream = inStreamRec.read(byterecv)) != -1) {
System.out.println("startrec bytearray -- "
+ byterecv.length);
bos1.write(byterecv, 0, lstream);
}
inStreamRec.close();// for closing dataouputstream
clientRec.close();// for closing socket connection
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my receiver and player code..
/**
* start receiving the voice data from server
* */
protected void startplay() {
System.arraycopy(frndid, 0, playByteData, 0, 4);
System.arraycopy(userid, 0, playByteData, 4, 4);
ByteBuffer.wrap(sessionid).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().
put(call_sessionid);
System.arraycopy(sessionid, 0, playByteData, 8, 4);
int lstream;
int port = 1014;
while (true) {
System.out.println("POOL-3");
try {
if (stopcall == true) {
System.out.println("BREAKEDDDD1111");
//break;
}
// Host name
// port++;
InetAddress addressPlay = InetAddress.getByName("192.168.1.36");
// Creates a new streaming socket connected to the target host
Socket clientPlay = new Socket(addressPlay, port);
System.out.println("Just connected to play : " +
clientPlay.getRemoteSocketAddress());
System.out.println("SENTS Play BEFORE");
// output streams that write data
OutputStream outToServer = clientPlay.getOutputStream();
DataOutputStream outStreamPlay = new DataOutputStream(outToServer);
outStreamPlay.write(playByteData);
System.out.println("SENTS Play after");
// input streams that read data
InputStream inFromServerPlay = clientPlay.getInputStream();
DataInputStream inStreamPlay = new DataInputStream(inFromServerPlay);
//clientPlay.setSoTimeout(5000);
while ((lstream = inStreamPlay.read(byteArray)) != -1) {
System.out.println("startplay() bytearray -- " +
byteArray.length);
bos.write(byteArray, 0, lstream);
}
inStreamPlay.close();
clientPlay.close();// for closing play socket connection
responseBuffer = bos.toByteArray();
System.out.println("BAOSSIZE " + bos.size());
bos.reset();
bos.flush();
bos.close();
playing = true;
System.out.println("res length -- " + responseBuffer.length);
rcvbb=ByteBuffer.wrap(responseBuffer).order(ByteOrder.LITTLE_ENDIAN).
asShortBuffer().get(playShortData);
playVoiceReceived();// plays received data
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* start playing received the voice data from server
* */
public void playVoiceReceived() {
System.out.println("POOL-4");
try {
if (at != null) {
if (at.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
at.play();// starts playing
} else {
System.out.println("Play BEFORE WRITE");
// Writes the audio data to the audio hardware for playback.
at.write(playShortData, 0, BufferElements2Play);
System.out.println("Play AFTER WRITE");
at.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The socket has sent the data ... to the local socket send buffer. What happens after that is up to the local TCP stack, the network, the remote TCP stack, and the remote application. If you want to know whether the remote application got the data, it will have to send you a reply.
Operator write does not check whether data was delivered because otherwise it would have to wait for too long time. If network connection is actually down, TCP layer of operating system, will try to send data anyway, but will detect problems somewhat later, i.e. 1 minute later, because it will not receive acknowledgement messages from the opposite side. It will then try to resend data several times, see that problem persists and only then will report exception condition on the socket. To know that socket is in exception condition, you need to perform some operator on socket, i.e. another write attempt. Try doing write in a loop like this:
while (true)
{
outStreamRec.write (data);
Thread.sleep (1000L);
}
It should throw an error about 2 minutes after network will be down.
Note, that in opposite to write operation, operation connect is synchronous, so it actually waits for response from the opposite side, and if there is not respose, it will throw an exception.
I am building a small chat application in which client A wants to send something to client C with server B in between. First of all is this a correct approach for the problem??. I am able to send and receive data to and from a server but it is limited to only the client.For example if Client A sends data to server B and client C is sending data to server B then i can send data back to A and C just like an echo server. But what i want is to forward data coming from Client A to Client C via server B.
The following is the server code:
public class Server {
public static void main(String[] args) {
int port = 666; //random port number
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client....");
System.out.println("Got a client :) ... Finally, someone saw me through all the cover!");
System.out.println();
while(true) {
Socket socket = ss.accept();
SSocket sSocket = new SSocket(socket);
Thread t = new Thread(sSocket);
t.start();
System.out.println("Socket Stack Size-----"+socketMap.size());
}
}
catch (Exception e) { }
}
}
class SSocket implements Runnable {
private Socket socket;
public SSocket(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dIn = new DataInputStream(in);
DataOutputStream dOut = new DataOutputStream(out);
String line = null;
while (true) {
line = dIn.readUTF();
System.out.println("Recievd the line----" + line);
dOut.writeUTF(line + " Comming back from the server");
dOut.flush();
System.out.println("waiting for the next line....");
}
}
catch (Exception e) { }
}
}
The client code is :
public class Client {
public static void main(String[] args) {
int serverPort = 666;
try {
InetAddress inetAdd = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(inetAdd, serverPort);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dIn = new DataInputStream(in);
DataOutputStream dOut = new DataOutputStream(out);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Type in something and press enter. Will send it to the server and tell ya what it thinks.");
System.out.println();
String line = null;
while (true) {
line = keyboard.readLine();
System.out.println("Wrinting Something on the server");
dOut.writeUTF(line);
dOut.flush();
line = dIn.readUTF();
System.out.println("Line Sent back by the server---" + line);
}
}
catch (Exception e) { }
}
}
When your clients connect to the server, your server creates a Socket for it, here it is Socket socket = ss.accept();, your socket variable will be holding that client.
now if you just keep adding your client socket to a arraylist in your while loop, you will have a list of clients actively connected with your server like:
after the accept:
clients = new ArrayList<DataOutputStream>();
Socket socket = ss.accept();
os = new DataOutputStream(socket.getOutputStream());
clients.add(os);
Now as you have all the clients in that clients arraylist, you can loop through it, or with some protocol define which client should i send the data after reading.
Iterator<DataOutputStream> it = clients.iterator();
while ((message = reader.readLine()) != null) { //reading
while (it.hasNext()) {
try {
DataOutputStream oss = it.next();
oss.write(message);//writing
oss.flush();
}
catch (Exception e) { }
}
}
This will loop through all the available clients in the arraylist and will send to all. you can define ways to send to only some.
For example:
maintain a ActiveClients arraylist and with some GUI interaction may be or maybe, define what all clients you want to send the message.
Then add just those clients outputStreams to ActiveClients
ActiveClients.add(clients.get(2));
or remove them, if you don't want them.
ActiveClients.remove(clients.get(2));
and now just loop through this arraylist to send the data as above.
You can create message queue for each client:
Client A sends message 'Hi' with address Client C to server B.
Server B receives message and adds it to message queue of client C.
Thread in server B which communicates with client C check message queue, retrieve message and sends it to client C.
Client C receives message.
If I am not mistaken, you must be having a problem with receiving a message from the Server or SSocket class. What happens with your code is that when you send a message from the client to the server the Server class receives your messages also gives an echo of the message in the client. However, when you send a message from the Server class, you don't get any messages in the Client Class.
To get this to work, you would have to modify your code in the following fashion:
SSocket Class
String line = null;
while (true) {
line = dIn.readUTF();
System.out.println("Recievd the line----" + line);
dOut.writeUTF(line + " Comming back from the server");
dOut.flush();
System.out.println("waiting for the next line....");
}
You should add these lines:
String Line2 = take.nextLine(); //The user types a message for the client
dOut.writeUTF(Line2 + " Comming back from the server"); //The message is sent to the client
Replace the while loop with this one and it will work fine.
while (true) {
line = dIn.readUTF(); //Takes the msg from the client
System.out.println("Recievd the line----" + line); //Prints the taken message
String Line2 = take.nextLine(); //The user types a message for the client
dOut.writeUTF(Line2 + " Comming back from the server"); //The message is sent to the client
dOut.flush();
System.out.println("waiting for the next line....");
}