mardi 24 juin 2014

How to connect 2 different computers on a network using a chat application in Java?


Vote count:

0




I have a simple pair of client and server programs. Client connects to server and when it does connect, the server replies with a "Hello there" message. How should I modify the program if I want the client and server programs to run on different systems?


Here is the code for the client side..



package practice;

import java.io.*;
import java.net.*;

public class DailyAdviceClient
{
public static void main(String args[])
{
DailyAdviceClient dac = new DailyAdviceClient();
dac.go();
}

public void go()
{
try
{
Socket incoming = new Socket("127.0.0.1",4242);
InputStreamReader stream = new InputStreamReader(incoming.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String advice = reader.readLine();
reader.close();
System.out.println("Today's advice is "+advice);
}
catch(Exception e)
{
System.out.println("Client Side Error");
}
}
}


and here is the code for the server



package practice;

import java.io.*;
import java.net.*;

public class DailyAdviceServer
{
public static void main(String args[])
{
DailyAdviceServer das = new DailyAdviceServer();
das.go();
}

public void go()
{
try
{
ServerSocket serversock = new ServerSocket(4242);

while(true)
{
Socket outgoing = serversock.accept();
PrintWriter writer = new PrintWriter(outgoing.getOutputStream());
writer.println("Hello there");
writer.close();

}
}
catch(Exception e)
{
System.out.println("Server Side Problem");
}
}
}


asked 55 secs ago






Aucun commentaire:

Enregistrer un commentaire