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.
Related
When i run my code it's working fine but after some hours it stop working and show this error Not able to publish: MQTT client is not connected
public Mqtt5AsyncClient connect(String host, int port) {
Mqtt5AsyncClient client = MqttClient.builder().useMqttVersion5()
.identifier(UUID.randomUUID().toString())
.serverHost(host)
.serverPort(port).buildAsync();
Mqtt5ConnAck connectionAck = null;
try {
connectionAck = client.toBlocking().connect();
Mqtt5ConnAckReasonCode connAckCode = connectionAck.getReasonCode();
logger.debug("Client connected to broker with url: " + host + ":" + port + " ::Connection ack code: " + " keep alive ");
} catch (Exception ex) {
logger.debug("Not able to connect to broker with url: " + host + ":" + port);
ex.printStackTrace();
}
return client;
}
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.
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?
I've made a java application which uses UDP and I can't seem to receive packets outside LAN when hosting on my computer. I tried putting my application on a Hosted Server and it seemed to work (receives packet).
What is causing this to happen? I want it to work on my computer as well.
CLIENT:
try {
this.socket = new DatagramSocket(2500);
} catch (SocketException e1) {
System.out.println("Could not establish connection");
return;
}
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try{
socket.receive(packet);
}catch(IOException e){
System.out.println("Connection close");
break;
}
System.out.println("RECEIVED " + new String(packet.getData()));
}
SERVER:
try {
this.socket = new DatagramSocket(25860);
} catch (SocketException e) {
e.printStackTrace();
}
try {
byte[] data = datas.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 2500);
socket.send(packet);
}catch(IOException e) {
}
System.out.println("Sent " + ipAddress.getHostAddress() + ":" + port + " " + new String(datas));
IP Address is correct, it exactly prints out the same IP as my CLIENT. However I'm still not receiving.
If it works in one computer (single) and not on the other try checking the firewall, UDP connections should be allowed in your computer.
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.