I created server client app in eclipse. I block firewall and running perfectly. I run server.java
and client.java
in different computers.There is no problem. I have hardcoded server's ip in client.java
(for e.g.: 10.10.154.10).
I have a question for server's ip. client.java
running in another computer. From server.java
how can I find server ip automatically?
Server.java
import javax.swing.*;
import javax.swing.text.html.HTMLDocument.Iterator;
public class Server extends JFrame {
private ServerSocket serverSock;
private int port;
public static void main(String[] args) {
new Server();
}
public Server() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
port = 1453;
try {
InetAddress inet = InetAddress.getLocalHost();
String adres = inet.getHostAddress();
JPanel panel = new JPanel();
panel.add(new JLabel("Server Address:"));
txtAdres = new JTextField(7);
panel.add(txtAdres);
txtAdres.setText(adres);
txtAdres.setEditable(false);
panel.add(new JLabel("Port:"));
txtPort = new JTextField(5);
panel.add(txtPort);
txtPort.setText(String.valueOf(port));
panel.add(btnStart);
panel.add(btnStop);
btnStop.setEnabled(false);
add(panel, BorderLayout.NORTH);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
btnActionStartClass actionStart = new btnActionStartClass();
btnActionStopClass actionStop = new btnActionStopClass();
btnStart.addActionListener(actionStart);
btnStop.addActionListener(actionStop);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
setLocationRelativeTo(null);
}// end of contructor
class btnActionStartClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
btnStart.setEnabled(false);
btnStop.setEnabled(true);
Thread starter = new Thread(new ServerStarter());
starter.start();
jta.append("Server started at " + new Date()+"\n");
}
}//end of actionstartclass
class btnActionStopClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
btnStart.setEnabled(true);
btnStop.setEnabled(false);
try {
serverSock.close();
jta.append("Server is closed. \n");
messageToClients("Server is closed..");
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}//end of actionstopclass
class ServerStarter implements Runnable{
@Override
public void run() {
broadcast = new ArrayList();
try{
port = Integer.parseInt(txtPort.getText().trim());
serverSock = new ServerSocket(port);
while(true){
Socket socket = serverSock.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
broadcast.add(writer);
Thread listener = new Thread(new ThreadClient(socket, writer));
listener.start();
jta.append("Connection Success!\n");
}
}
catch(Exception e){
jta.append("Error making a connection. \n");
}
}
}//end ServerStarter
class ThreadClient implements Runnable {
private Socket socket;
private PrintWriter writer;
BufferedReader reader;
public ThreadClient(Socket socket, PrintWriter writer) {
this.writer = writer;
try{
this.socket = socket;
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch(Exception e){
jta.append("Unexpected error.. \n");
}
}
@Override
public void run() {
String message;
String[] arr;
try{
while((message = reader.readLine()) !=null){
//jta.append("Received: "+ message + "\n");
arr = message.split(":");
if(arr[2].equals("Connect")){
messageToClients((arr[0] + ":" + arr[1] + ":" + "Chat"));
}
else if (arr[2].equals("Chat"))
{
messageToClients(message);
}
else
{
jta.append("No Conditions were met. \n");
}
}
}
catch(Exception ex){
jta.append("Lost a connection. \n");
ex.printStackTrace();
broadcast.remove(socket);
}
}//end-RUN
}//end-ThreadClient
public void messageToClients(String message){
java.util.Iterator iter = broadcast.iterator();
while(iter.hasNext()){
try{
PrintWriter writer = (PrintWriter)iter.next();
writer.println(message);
//jta.append("Sending: "+ message+ "\n");
writer.flush();
jta.setCaretPosition(jta.getDocument().getLength());
}
catch(Exception e){
jta.append("Error telling everyone. \n");
}
}
}
}
Client.java
public class Client extends JFrame {
tfAddress.setText("localhost");
tfPort.setText("1453");
//////////////Panel TOP
panelTop.setLayout(new FlowLayout());
panelTop.add(lbl1);
panelTop.add(tfAddress);
panelTop.add(lbl2);
panelTop.add(tfPort);
panelTop.add(btnLogin);
add(panelTop, BorderLayout.NORTH);
//////////////Panel CENTER
jta.setEditable(false);
add(jta, BorderLayout.CENTER);
//////////////Panel BOTTOM
panelBottom.setLayout(new FlowLayout());
tfInput = new JTextField(30);
btnSend = new JButton("Send");
panelBottom.add(tfInput);
panelBottom.add(btnSend);
add(panelBottom, BorderLayout.SOUTH);
loginActionClass loginAction = new loginActionClass();
sendActionClass sendAction = new sendActionClass();
btnLogin.addActionListener(loginAction);
tfInput.addActionListener(sendAction);
btnSend.addActionListener(sendAction);
}//end-of-constructor
public class threadReaderClass implements Runnable
{
@Override
public void run() {
String[] data;
String coming;
String connect = "Connect";
String chat = "Chat";
try{
while((coming = reader.readLine()) != null){
data = coming.split(":");
if(data[2].equals("Chat"))
{
jta.append(data[0] + ":" + data[1] + "\n");
jta.setCaretPosition(jta.getDocument().getLength());
}
}
}
catch(Exception e){
}
}
}//end-threadReaderClass
public class loginActionClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(isConnected == false ){
String anonymous = "anonymous";
String value = String.valueOf((new Random().nextInt(999) +1));
anonymous = anonymous.concat(value);
username = anonymous;
try {
address = tfAddress.getText().trim();
port = Integer.parseInt(tfPort.getText().trim());
socket = new Socket(address, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
writer.println(username + ":has connected.:Connect");
writer.flush();
isConnected = true;
} catch (UnknownHostException e1) {
jta.append("Cannot connect :/ please try again \n" );
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//go! for open thread for incoming..!
Thread threadReaderClass = new Thread(new threadReaderClass());
threadReaderClass.start();
/////////////////////////////////////
}//end-if
else if(isConnected == true){
jta.append("You are already connected. \n");
}
}
}
public class sendActionClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if((tfInput.getText()).equals("")){
tfInput.setText("");
tfInput.requestFocus();
}
else
{
try{
writer.println(username + ":" + tfInput.getText() + ":" + "Chat");
writer.flush();
}catch(Exception de){
jta.append("message dont go --> --> --\\>");
}
tfInput.setText("");
tfInput.requestFocus();
}
}
}
public static void main(String Args[]) {
Client frame = new Client();
frame.setTitle("Client");
frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}