The problem i have is that when i open a second client, the server doesn't seem to detect that a second client was opened. With the first time the client being opened it works fine and the server detects that a client has been connected.
Server:
public class Server {
Socket previousSocket = null;
private static int port = 9001;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("[SERVER] Server successfully launched on port: " + port);
DatagramSocket UDPSocket = new DatagramSocket(9002);
Socket previousSocket = null;
while (true) {
Socket newSocket = serverSocket.accept();
System.out.println("new client connected");
if (previousSocket == null) {
previousSocket = newSocket;
System.out.println("1 st client");
} else {
System.out.println("2 nd client");
previousSocket = null;
}
byte[] data = new byte[500];
DatagramPacket received = new DatagramPacket(data, data.length);
while(true) {
UDPSocket.receive(received);
String receivedData = new String(received.getData());
System.out.println(receivedData);
}
}
}
}
Client:
public ChatClient() throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 9001);
Scanner scanner = new Scanner(System.in);
DatagramSocket UDPSocket = new DatagramSocket();
while(scanner.hasNextLine()) {
String message = scanner.nextLine();
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, 9002);
UDPSocket.send(packet);
}
}
The following loop will never end, that's the reason for your problem
while(true) {
UDPSocket.receive(received);
String receivedData = new String(received.getData());
System.out.println(receivedData);
}
Related
i have an ISO8583 message to send between a client and a server (through sockets). What i did is declare socket and serverSockets classes, start server and accept connections, then create channel both on server and client to apply receive and send methods.
What i got is i cannot print the iso8583 message i send. here is the complete code :
The server's side code :
public class SocketServer {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void start(int port) throws IOException, ISOException {
serverSocket = new ServerSocket(port);
clientSocket = serverSocket.accept();
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r = channel.receive ();
System.out.println("isoMsg result "+r.getMTI());
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String data = in.readLine();
System.out.println("Inside Server Socket: " + data);
out.println("Data from server: " + data);
}
public void stop() throws IOException {
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException, ISOException {
SocketServer server = new SocketServer();
server.start(5000);
System.out.println("Server start...");
}
}
and the client's code :
public class Client
{
public Client(String address, int port) throws ISOException
{
// establish a connection
try
{
Socket socket = new Socket(address, port);
System.out.println("Connected");
ISOChannel channel = new ASCIIChannel (
"localhost", 5000, new ISO87APackager() );
channel.connect();
ISOMsg r=new ISOMsg();
r.setMTI("0200");
channel.send(r);
InputStream in2= socket.getInputStream();
OutputStream out2=socket.getOutputStream();
String line = "";
try
{
in2.close();
out2.close();
socket.close();
}
catch(IOException i)
{
i.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws ISOException
{
Client client = new Client("localhost", 5000);
}
}
I have tomcat installed on vps, everything has been configured, but how do I host my java server on it? What extension should I use and which folder should I put? Or do I need to change something in the Server.java?
Here he is:
public class Server {
public static void main(String[] ar) throws IOException {
int port = 8080;
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
System.out.println("Got a client!");
System.out.println();
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
String line = null;
while(true) {
line = in.readUTF();
System.out.println("The dumb client just sent me this line : " + line);
System.out.println("I'm sending it back...");
out.writeUTF(line);
out.flush();
System.out.println("Waiting for the next line...");
System.out.println();
}
} catch(Exception x) { x.printStackTrace(); }
}
}
Client program
public class client implements Runnable {
protected static String server_IP = "141.117.57.42";
private static final int server_Port = 5555 ;
protected static String client_IP ;
public static void main(String[] args) throws IOException{
final String host = "localhost";
int init = 0 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
client_IP = iAddress.getHostAddress();
System.out.println("Current IP address : " +client_IP);
} catch (UnknownHostException e) {
}
try {System.out.println("hello1");
Socket socket = new Socket(server_IP,server_Port);
System.out.println("hello3");
init = initialize(socket);
}catch (SocketException e) {
System.out.println("Error: Unable to connect to server port ");
}
if (init == 0 ){
System.out.println("error: Failed to initialize ");
System.exit(0);
}
//Thread init_Thread = new Thread();
}
private static int initialize(Socket socket ) throws IOException{
System.out.println("hello");
int rt_value = 0 ;
OutputStream os = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
System.out.println("server: " + br.readLine());
pw.println("192.343.34.321");
// BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
//String userInput = userInputBR.readLine();
//out.println(userInput);
socket.close();
return rt_value = 1 ;
}
public void run(){
}
}
server side program
public class server {
protected static String server_IP ;
public static void main(String[] args) throws IOException {
int server_Port = 5555 ;
try {
InetAddress iAddress = InetAddress.getLocalHost();
server_IP = iAddress.getHostAddress();
System.out.println("Server IP address : " +server_IP);
} catch (UnknownHostException e) {
}
ServerSocket serverSocket = new ServerSocket(server_Port);
while (true) {
Socket socket = serverSocket.accept();
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
pw.println("Connection confirmed ");
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
pw.println("your ip address is " + str);
pw.close();
//socket.close();
//System.out.println("Just said hello to:" + str);
}
How do I connect to the server socket using the ip address and port number (client is running on a different machine than server).
When I change the server_IP in client to "local host", it works perfectly.
To connect in your code you use:
Socket socket = new Socket(server_IP,server_Port);
So you could use:
Socket socket = new Socket("192.168.1.4", 5555);
It looks like you have this in your code so I'm not sure what problem you're having.
Don't forget that you have to setup your router to forward ports if it is located outside of your local network.
http://www.wikihow.com/Set-Up-Port-Forwarding-on-a-Router
Don't forget that if you are running a firewall, this can also interfere with the connection.
Update /etc/hosts
Add following line
127.0.1.1 192.168.10.109
I have a UDP multicast server listening on 2 sockets on 2 different ports. I achieved listening on these 2 sockets from clients. But i want to identify on which socket a client is sending a packet. Since my problem is that ; on the server if I listen on socket(9999) and if the client is sending on socket(8888) then at the server side I want it to identify the incoming packet is from which port.
public class MulticastReceiver
{
public static void main(String[] args)
{
MulticastSocket socket = null;
DatagramPacket packet = null;
MulticastSocket soc = null;
byte[] inBuf = null;
try
{
socket = new MulticastSocket(8888);
soc = new MulticastSocket(9999);
InetAddress address = InetAddress.getByName("224.2.2.3");
socket.joinGroup(address);
soc.joinGroup(address);
System.out.println("224.2.2.3 ready to receive packets");
while(true)
{
inBuf=new byte[256];
packet = new DatagramPacket(inBuf,inBuf.length);
System.out.println("port is: "+ packet.getAddress() + packet.getPort());
if(packet.getPort() == 9999)
{
soc.receive(packet);
//System.out.println("Data at 224.2.2.3:: " + new String(packet.getData()));
}
else
socket.receive(packet);
System.out.println("Data at 224.2.2.3:: " + new String(packet.getData()));
}
}
catch(Exception e)
{
}
}
}
public class MulticastSender {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket outPacket = null;
byte[] outBuf;
final int PORT = 8888;
try {
socket = new DatagramSocket();
long counter = 0;
String msg;
msg = "This is multicast! ";
outBuf = msg.getBytes();
//Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
public class AnotherSender {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket outPacket = null;
byte[] outBuf;
final int PORT = 9999;
try {
socket = new DatagramSocket();
long counter = 0;
String msg;
msg = "This is another multicast! " + counter;
counter++;
outBuf = msg.getBytes();
//Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
Your code doesn't make sense. The packet won't have a port number at all until you put one into it or receive() does, and at best this will just read alternately between the two sockets, blocking each time, possibly forever, receiving from one socket, and thus starving the other one.
You need a receiving thread for each non-blocking socket.
I have a client and a server. The client binds a socket on a specific port, the server sends back a new port to the client and the client should bind a new socket on the new port number.
From the main server thread, I start a thread that sends a message to the client once the server is ready and is listening to the new port, so that the client can attempt to connect to the new port. The pipe from the child thread is not sending the message to the client.
So both client and server just freeze, it seems like a deadlock, but im not sure. This line of code in the client: System.out.println("FROM SERVER: " + inMsg_rport); is not executing.
Server Code:
class server
{
public static void main(String argv[]) throws Exception
{
String newPort;
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(5555);
clientSocket = serverSocket.accept();
DataOutputStream serverOut =
new DataOutputStream(clientSocket.getOutputStream());
int r_port = 5556;
Thread appThread = new Thread(new serverApp(serverOut, r_port));
appThread.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
static class serverApp implements Runnable
{
DataOutputStream serverOut;
int nPort;
public serverApp(DataOutputStream servO, int r_port)
{
this.serverOut = servO;
this.nPort = r_port;
}
#Override
public void run()
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
try
{
serverSocket = new ServerSocket(nPort);
serverOut.writeBytes(sr_port);
clientSocket = serverSocket.accept();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
}
Client code:
class client {
public static void main(String argv[]) throws Exception
{
String serverIp = argv[0];
String msg = argv[2];
int port = Integer.parseInt(argv[1]);
Socket clientSocket = new Socket(InetAddress.getByName(serverIp), port);
BufferedReader clientIn =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inMsg_rport = clientIn.readLine();
System.out.println("FROM SERVER: " + inMsg_rport);
int r_port = Integer.parseInt(inMsg_rport);
clientSocket.close();
System.out.println("Closed connection");
Socket new_clientSocket = new Socket(InetAddress.getByName(serverIp), r_port);
}
}
readLine() in your client is a blocking call, waiting for an end-of-line character
http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#readLine()
You aren't sending an end of line character. You're using a DataOutputStream in your server and sending raw bytes.
Don't use a DataOutputStream in your server; I don't think that's really what you're looking for. Just send the port number as text with an end of line character and be done with it.