TCP/IP Sending request and getting response - java

I am Working on TCP/IP in Java. First, I read TCP/IP and understand how it's working.
What i Need:-
Ok, Now i want to implement it in java. I am trying to Send some input in request to specific port/IP from my IP. and need to get response.
I don't understand how to implement it.
Here is my Input:
Destination IP
Destination Port
Input(String or Anything)
Here is my code which i use for Client.
try {
socket = new Socket("localhost", port);
}
catch(Exception e) {
System.out.println("Error connectiong to server:" + e);
return;
}
System.out.println("Connection accepted " +
socket.getInetAddress() + ":" +
socket.getPort());
/* Creating both Data Stream */
try
{
Sinput = new ObjectInputStream(socket.getInputStream());
Soutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException e) {
System.out.println("Exception creating new Input/output Streams: " + e);
return;
}
// now that I have my connection
String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
// send the string to the server
System.out.println("Client sending \"" + test + "\" to serveur");
try {
Soutput.writeObject(test);
Soutput.flush();
}
catch(IOException e) {
System.out.println("Error writting to the socket: " + e);
return;
}
// read back the answer from the server
String response;
try {
response = (String) Sinput.readObject();
System.out.println("Read back from server: " + response);
}
catch(Exception e) {
System.out.println("Problem reading back from server: " + e);
}
try{
Sinput.close();
Soutput.close();
}
Please give me some hint or reference.

Creating Scoket
go through this will help you.
if you are implementing Sockets, you need to use ServerSocket class to create the ServerSocket . Then Socket class to request the create the connection between Client and Sever.

Related

Keep Alive Socket between Java client and VB Server

I've created program to send and get data from client to server and for client i used java and server I used Visual Basic so how to set the connection between client and server is keep alive in a client(java) side?
this is the code from client :
public static void Client(){
String print = "";
String dataDB = "Hello server, From Client";
try(Socket clientSocket = new Socket("localhost", port)){
clientSocket.getOutputStream().write(dataDB.getBytes("ASCII"));
while (clientSocket.getInputStream().available() == 0) {
Thread.sleep(100L);
}
byte[] data = new byte[clientSocket.getInputStream().available()];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
print = new String(data, 0, bytes, "ASCII");//.substring(4,bytes);
while(print.length()>0){
System.out.println("From Server : "+print);
}
}catch (IOException ex){
System.out.println("I/O error: " + ex.getMessage());
}catch(InterruptedException ie){
System.out.println("error: " + ie.getMessage());
}catch(Exception e){
System.out.println("error: " + e.getMessage());
}
}
The Java client is a console application, just sent and get data from server i tried to used clientSocket.setKeepAlive(true); but is not working.

Server Socket Isn't Sending Data Back in Java

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

How to deploy 3 instances of a server on localhost?

Below is the code I will run to spawn a server on my localhost.
However I want 3 instances of server code to run on ports 5000, 6000, 7000.
I can think of creating 3 .java files each hard coded with different port number.
But is there a better way to spawn 3 server instances on localhost without cut copy pasting 3 files ?
public void startServer() {
try {
ServerSocket welcomeSocket = new ServerSocket(5000);
while (true) {
// Create the Client Socket
Socket clientSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
Message m = (Message) inFromClient.readObject();
System.out.println("---- hello: my message is: " + m.name);
}
} catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
You can do this:
public void startServer(int port) {
try {
ServerSocket welcomeSocket = new ServerSocket(port);
while (true) {
// Create the Client Socket
Socket clientSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
Message m = (Message) inFromClient.readObject();
System.out.println("---- hello: my message is: " + m.name);
}
} catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
And now, just call:
startServer(5000);
startServer(6000);
startServer(7000);
Or, even better: use a loop to start the servers three times.

No address in DatagramPacket

I am attempting to add a multiplayer form to a simple pong game, but when I try to start the DatagramPacket and try to read the IP and port it says the ip is null and the port is -1. Does anyone know why it would be doing this? I thought maybe it was because the socket hadn't recieved the packet yet, but when I look I saw that all code after socket.recieve(packet) isn't running.
Code where I start the server:
public GameServer(PongEngine engine) {
this.engine = engine;
try {
this.socket = new DatagramSocket(4269);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
System.out.println(packet.getAddress() + ":" + packet.getPort());
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
String message = new String(packet.getData());
if(message.trim().equalsIgnoreCase("ping")) {
System.out.println("CLIENT[" + packet.getAddress() + ":" + packet.getPort() + "] > " + message);
sendData("pong".getBytes(), packet.getAddress(), packet.getPort());
}
}
}
DatagramPacket's getAddress returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.
In the first System.out.println you have just created the object, but have not done any network I/O with it.
Then you ignore the exception and just try to work with the datagram. If there was an I/O error, it's likely that the datagram was not initialized and hence still has IP address null and port -1.
If nothing happens after socket.receive() I'd assume the call is blocked, waiting for a packet to come in. Do you actually run the client that connects to your server code?
To add to Roberts answer, your code is simply out of order. Once you have that fixed then you can address why you might not be recieving a packet form the other PC like ccarton suggested.
Try this, and note the two comments
public void run() {
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
//Wait for packet (The code will not move on until a packet is received or there is an error)
System.out.println("Waiting for packet");
socket.receive(packet);
//Move your socket/port info after receiving a packet so you don't get null or -1
System.out.println("Packet received: "+ packet.getAddress() + ":" + packet.getPort());
//Move your code inside try, rather than after
String message = new String(packet.getData());
if(message.trim().equalsIgnoreCase("ping")) {
System.out.println("CLIENT[" + packet.getAddress() + ":" + packet.getPort() + "] > " + message);
sendData("pong".getBytes(), packet.getAddress(), packet.getPort());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now do you still get the same issues?

ObjectInputStream does not work with Sockets

a few days ago, I started to code a little multiplayer game, in wich I use ObjectInputStreams and ObjectOutputStreams in order to exchange data with a server. But for some reason, the server does not recieve anything. So I searched for some help, but everything I found was, that I have to flush the ObjectOutputStream. Of course I did this, but it is not the solution for my problem. So I wrote a tiny test application, that does the same as my game. But there is still the same problem: The InputStream does not recieve anything. So here's my code for the test app:
Server application:
try {
ServerSocket srvr = new ServerSocket(12975);
Socket client = srvr.accept();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.flush();
System.out.println("server ready!");
String line = "";
while(!line.equalsIgnoreCase("exit")){
while(in.available() <= 0){}
line = in.readObject().toString();
System.out.println(">>> recieved: " + line);
}
client.close();
srvr.close();
System.exit(0);
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
And here's the client application:
try {
Socket client = new Socket("localhost", 12975);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
System.out.println("client ready!");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while(!line.equalsIgnoreCase("exit")){
System.out.print("> ");
line = input.readLine();
out.writeObject(line);
out.flush();
}
client.close();
System.exit(0);
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
I tried to do this to both sides: Server->Client and Client->Server, but both Sockets did not recieve anything. Any research failed, because everyone seems to forget the flush() after constructing the OutputStream, but then it works.
So I hope, anyone knows this problem and is able to help me.
P.S: I am not from England nor from America, so sorry, if my English contains mistakes! :D
Just try this , this is working.
while(!line.equalsIgnoreCase("exit")){
while(in.available() <= 0){
line = in.readObject().toString();
System.out.println(">>> recieved: " + line);
}
}
You have mistaken with your second while loop parenthesis in server code.

Categories

Resources