I have two doubts
FIRST.
I am creating a desktop application in netbeans, I want to open a port entered by user.I have created two files in same package, getting port number from user its in one file and processing on it is second file.
I have created object of that class for getting user's entered port number its not showing any error but port is not opening on that number i have checked using tcp view
here is code of first file
Server.java
package server;
import java.io.*;
import java.net.*;
import javax.swing.JFrame;
public class Server extends Thread {
public static int SERVERPORT;
private boolean running = false;
public volatile boolean stop = false;
public Socket client = null;
public static void main(String[] args) {
mainFrame frame = new mainFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
SERVERPORT = frame.portnum;//here i am getting port number from 2nd file
}
#Override
public void run() {
super.run();
running = true;
try {
System.out.println("Server Has Started........ \n Waiting for client........");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
try {
while (!stop && running) {
client = serverSocket.accept();
System.out.println("Connection Accepted......");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String usercmnd = in.readLine();
if (usercmnd != null) {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(usercmnd);
}
}
here is 2nd file where user have to enter a port number
mainFrame.java
package server;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.net.*;
//import server.Server;
/**
*
* #author admin
*/
public class mainFrame extends JFrame {
private Server mServer;
public int portnum;
public mainFrame() {
super("mainFrame");
mServer = new Server();
initComponents();
setIcon();labInfo.setText("Not Connected");
try{ ipAdd.setText(String.valueOf(InetAddress.getLocalHost().getHostAddress()));
}catch(Exception e){labInfo.setText(e.getMessage());}
}
private void connActionPerformed(java.awt.event.ActionEvent evt) {
if(port.getText().equals(""))
{
labInfo.setText("Port number cannot be empty!!");
}else{
portnum=Integer.parseInt(port.getText());//here i am getting user's entered port number
conn.setEnabled(false);port.setEditable(false);
labInfo.setText("Waiting for Connection.....");
mServer.start();
}
}
private void disconnActionPerformed(java.awt.event.ActionEvent evt) {
mServer.requestStop();
labInfo.setText("Not Connected");
port.setEditable(true);
conn.setEnabled(true);
}
SECOND.
Is there any way to check entered port number is currently using so then we can alert the user to use another port number...???
I would rather suggest you run the mainFrame class first from which you can call the Server class at the click of the Button to retrieve the port number entered in the TextField. I can't seem to help with the full code but you can change your connActionPerformed() method to
private void connActionPerformed(java.awt.event.ActionEvent evt) {
boolean success = false;
do {
try {
if (port.getText().equals("")) {
labInfo.setText("Port number cannot be empty!!");
} else {
portnum = Integer.parseInt(port.getText());//here i am getting user's entered port number
ServerSocket serverSocket = new ServerSocket(portnum);
System.out.println("Connected to Server");
mServer = new Server(serverSocket);//Which means you need to implement a constructor with a Server argument.
//conn.setEnabled(false);
//port.setEditable(false);
//abInfo.setText("Waiting for Connection.....");
mServer.start();
success = true;
}
} catch (BindException ex) {
System.out.println("Port in use");
}
} while (success);
}
And then you can implement a constructor like this:
ServerSocket serverSocket;
public Server(ServerSocket serverSoket){
this.serverSocket = serverSoket;
}
NOTE: since this code is not complete, manipulate to suit your needs.
Hope this would be helpful, thank you.
Related
I am trying to run a multi-user chat client java programme as part of another java programme.
How do I implement it in such a way that I can open up the chat client from the main programme? I have attempted to start it using ProcessBuilder but it causes the whole programme to crash.
The class to start the chat client and the client client itself is shown below respectively
--------------------- Class to start chat client ---------------------
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class ChatCommand extends Command {
public static final String COMMAND_WORD = "chat";
public static final String MESSAGE_USAGE = COMMAND_WORD + ":\n" + "Opens up a separate chat programme\n\t"
+ "Example: " + COMMAND_WORD;
public static final String MESSAGE_SUCCESS = "Initialising chat!";
public static void main(String[] args) {
new ChatCommand();
}
public ChatCommand() {
try {
int result = compile("seedu.addressbook.communications.ChatClient");
System.out.println("javac returned " + result);
result = run("seedu.addressbook.communications.ChatClient");
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
public int run(String clazz) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", clazz);
pb.redirectError();
pb.directory(new File("src"));
Process p = pb.start();
InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
consumer.start();
int result = p.waitFor();
consumer.join();
System.out.println(consumer.getOutput());
return result;
}
public int compile(String file) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("javac", file);
pb.redirectError();
pb.directory(new File("src"));
Process p = pb.start();
InputStreamConsumer consumer = new InputStreamConsumer(p.getInputStream());
consumer.start();
int result = p.waitFor();
consumer.join();
System.out.println(consumer.getOutput());
return result;
}
public class InputStreamConsumer extends Thread {
private InputStream is;
private IOException exp;
private StringBuilder output;
public InputStreamConsumer(InputStream is) {
this.is = is;
}
#Override
public void run() {
int in = -1;
output = new StringBuilder(64);
try {
while ((in = is.read()) != -1) {
output.append((char) in);
}
} catch (IOException ex) {
ex.printStackTrace();
exp = ex;
}
}
public StringBuilder getOutput() {
return output;
}
public IOException getException() {
return exp;
}
}
public CommandResult execute() {
ChatClient cc = new ChatClient();
try {
cc.main(new String[]{"a", "b"});
} catch (Exception e) {
System.out.println("aaa");
}
commandHistory.addHistory(COMMAND_WORD);
return new CommandResult(MESSAGE_SUCCESS);
}
}
--------------------------- Chat Client --------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/* A simple Swing-based client for the chat server. Graphically
* it is a frame with a text field for entering messages and a
* textarea to see the whole dialog.
*
* The client follows the Chat Protocol which is as follows.
* When the server sends "SUBMITNAME" the client replies with the
* desired screen name. The server will keep sending "SUBMITNAME"
* requests as long as the client submits screen names that are
* already in use. When the server sends a line beginning
* with "NAMEACCEPTED" the client is now allowed to start
* sending the server arbitrary strings to be broadcast to all
* chatters connected to the server. When the server sends a
* line beginning with "MESSAGE " then all characters following
* this string should be displayed in its message area.
*/
public class ChatClient {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("MediChat");
private JTextField textField = new JTextField(40);
private JTextArea messageArea = new JTextArea(8, 40);
/* Constructs the client by laying out the GUI and registering a
* listener with the textfield so that pressing Return in the
* listener sends the textfield contents to the server. Note
* however that the textfield is initially NOT editable, and
* only becomes editable AFTER the client receives the NAMEACCEPTED
* message from the server.
*/
public ChatClient() {
// Layout GUI
textField.setEditable(false);
messageArea.setEditable(false);
frame.getContentPane().add(textField, "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
// Add Listeners
textField.addActionListener(new ActionListener() {
/* Responds to pressing the enter key in the textfield by sending
* the contents of the text field to the server. Then clear
* the text area in preparation for the next message.
*/
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}
/* Prompt for and return the address of the server.
*/
private String getServerAddress() {
return JOptionPane.showInputDialog(
frame,
"Enter IP Address of the Server:",
"Welcome to MediChat!",
JOptionPane.QUESTION_MESSAGE);
}
/* Prompt for and return the desired screen name.
*/
private String getName() {
return JOptionPane.showInputDialog(
frame,
"Choose a screen name:",
"Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
/* Connects to the server then enters the processing loop.
*/
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 9001);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Process all messages from server, according to the protocol.
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}
/**
* Runs the client as an application with a closeable frame.
*/
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
You are seriously overcomplicating things:
don't make compiling your client code part of any Java class. Define a project setup in your IDE, or on the command line using gradle for example. Then use that to separately compile your classes whenever you change something. Running javac in your classes manually is seriously wrong!
and then, just make sure that all compiled class files are available on the classpath of your jvm. Don't bother to use reflection or anything else that is based on class names as raw strings.
most importantly: you use other classes by instantiating objects directly. The main method should only be used when you want to run a class standalone from the command line!
so instead of using class names as string, simply normally import the classes to use, and use new to create objects of them.
beyond that, separate your concerns. The client is the client, the server is the server. It is absolutely not a good idea to have the server start client instances. Meaning: rather create a third class, maybe called SetupTestEnvironment that first starts the server and a few clients for testing purposes.
import javax.swing.*;
import java.io.Serializable;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server implements Serializable{
public static void main(String[] args) {
String test1= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
int portnumber = tryParse(test1);
if (portnumber !=0) {
try {
Registry reg = LocateRegistry.createRegistry(portnumber); //Creates and exports a Registry instance on the local host that accepts requests
RmiImplementation imp = new RmiImplementation("C://ServerStorage");
reg.bind("remoteObject", imp);
System.out.println("Server is ready.");
System.out.println(portnumber);
} catch (Exception e) {
System.out.println("Server failed: " + e);
}
}
}
private static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (Exception e) {
return 0;
}
}
}
The above code helps me to set up my file server.
when the application is run, the dialog port number is requested.
If I type letters instead of numbers the program stops running, but I want it to continue and show me the dialog again.
Try with a do-while,
int portnumber = 0;
do {
String text= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
portnumber = tryParse(text);
}while(portnumber==0);
I'm experimenting with creating a socket application that sends some data from another application to a client. The code to access the data uses an abstract class.
SubscriptionAdapter listener = new SubscriptionAdapter() {
#Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
System.out.println(json.toString());
}
}
};
The mechanics of SubscriptionAdapter() were a little weird to figure out. onSubscriptionData gets called over and over and the for loop will return 1 to many records. Here is some sample output:
Yup
Got message: {"type":"lightning","location":{"coords":{"lon":18.509391,"lat":38.7581},"polarity":0}}
Yup
Got message: {"type":"lightning","location":{"coords":{"lon":18.504115,"lat":38.765076},"polarity":0}}
Got message: {"type":"lightning","location":{"coords":{"lon":18.494549,"lat":38.778813},"polarity":0}}
"Yup" is a line of debug code I put in above the for loop to confirm how the class functions.
Below is the sample socket server I'm working with:
import java.net.*;
import java.io.*;
public class Server {
/**
* #param args the command line arguments
*/
public static void main(String[] args) //throws Exception
{
try
{
ServerSocket serverSocket = new ServerSocket(9090);
System.out.println("Waiting for clients...");
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello client!");
out.close();
socket.close();
serverSocket.close();
} catch (Exception e)
{
System.out.println(e.toString());
}
}
}
The goal is to get System.out.println(json.toString()); to output to the socket connection. However, I've been running into scope issues.
I can't just put the code for the server inside onSubscriptionData because it will keep trying to create a new socket on a port that is already open.
I can't put the code OUTSIDE of the abstract class because then PrintWriter out = new PrintWriter(socket.getOutputStream(), true); winds up being out of scope.
I've been at it for a few hours and at this point, I could use some suggestions.
Update as requested. Below is the full code:
import com.satori.rtm.*;
import com.satori.rtm.model.*;
public class SubscribeToWeatherChannel {
static final String endpoint = [end point];
static final String appkey = [app key];
static final String channel = "full-weather";
public static void main(String[] args) throws InterruptedException {
final RtmClient client = new RtmClientBuilder(endpoint, appkey)
.setListener(new RtmClientAdapter() {
#Override
public void onEnterConnected(RtmClient client) {
System.out.println("Connected to Satori RTM!");
}
})
.build();
SubscriptionAdapter listener = new SubscriptionAdapter() {
#Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
System.out.println(json.toString());
}
}
};
client.createSubscription(channel, SubscriptionMode.SIMPLE, listener);
client.start();
}
}
Credit actually to Kayaman for the solution.
Don't create an anonymous instance of the abstract class. Create a
proper class that extends SubscriptionAdapter, then you can pass it
PrintWriters or any other things you need.
import com.satori.rtm.*;
import com.satori.rtm.model.*;
import java.net.*;
import java.io.*;
public class SpecificSubscriptionAdapter extends SubscriptionAdapter {
public static PrintWriter out;
public SpecificSubscriptionAdapter(PrintWriter out){
this.out = out;
}
#Override
public void onSubscriptionData(SubscriptionData data) {
for (AnyJson json : data.getMessages()) {
out.println(json.toString());
}
}
}
I have a multi threaded server in which server is waiting for all possible clients to be connected.As soon as client is connected it sends an int(12345) to server and server reads and display it now server uses a specific IPaddress of a client using hash map architecture sends a message to that client to which ipaddress is matched.but my code is stuck in while loop and it isn't go to the function messagetospecificclient() and if it goes it displays null. Sorry for my bad English
My code is
Server
public class ServerStart implements Runnable
{
#Override
public void run()
{
try
{
HandleMultipleClients hmc=new HandleMultipleClients();
hmc.connect();
hmc.messagetospecificclients("172.20.3.122");
}
}
HandleMultipleClients
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package zeeshannisar210;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*
* #author Zeeshan Nisar
*/
public class HandleMultipleClients{
Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();
Socket sock;
ServerSocket serverSock;
DataOutputStream dos;
DataInputStream dis;
String ip;
public HandleMultipleClients()
{
}
public void connect()
{
try
{
serverSock = new ServerSocket(2101);
while (true)
{
sock = serverSock.accept();
clients.put(sock.getPort(), sock);
dis=new DataInputStream(sock.getInputStream());
int s=dis.readInt();
System.out.print(s);
messagetospecificclients(ip);
}
}
catch(Exception e)
{
}
}
public void messagetospecificclients(String ipaddress) throws IOException
{
System.out.print(ipaddress);
for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); )
{
int key = iter.next();
System.out.print("ok1");
ip=ipaddress;
System.out.print(ip);
System.out.print("ok2");
java.net.Socket client = clients.get(key);
InetAddress zee = client.getInetAddress();
String s = zee.getHostAddress();
System.out.print("ok3");
System.out.print(s);
if (s.equals(ipaddress))
{
System.out.print("ok4");
dos =new DataOutputStream(client.getOutputStream());
dos.writeUTF("Some message");
}
}
}
public static void main(String[] args) {
new HandleMultipleClients();
}
}
Client code is
public class messagefromserver implements Runnable
{
#Override
public void run()
{
try
{
sock = new Socket("localhost",2101);
System.out.println("Success");
dos=new DataOutputStream(sock.getOutputStream());
dos.writeInt(12345);
// Basicinfosend bis=new Basicinfosend(sock);
// Thread t1=new Thread(bis);
// t1.start();
// Thread.sleep(1000);
// Systeminfosend sis=new Systeminfosend(sock);
// Thread t2=new Thread(sis);
// t2.start();
// Thread.sleep(1000);
// Thread p = new Thread(new Process());
// p.start();
while(true)
{
String s=dis.readUTF();
System.out.print(s);
}
}
i try to write simple messenger look like it's example in book(Java How To Program 9th Edition Paul Deitel Harvey Deitel, part 27.6). after i finished , i try to test it. it work on localhost(127.0.0.1), also work on computer which connect same modem (i mean ips such 192.168.0.1 and etc) but when i want to test it on some computer cross the internet a client side code got connection refused error.
i think when i client(which is my friend in somewhere in my city) try to connect server(which is me, again some where in city), when he enter my ip to connect me he connect to my modem and my modem don't send it's information to me(it's hard to explain something that u can't deeply understand it in none mother language so i'm sorry at all )
any help is important to me.
here is server code
//:D
//hello every Body:! this is my first program which use some networks !!! :-khatkeif
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.EOFException;
public class Server extends JFrame
{
JTextField enteredText;//input message from user
JTextArea displayArea;//display information to user
ObjectInputStream input;//input object from cilent
ObjectOutputStream output;//output Object to client
ServerSocket server;//server Socket
Socket connection;//connecton to cilent
public Server()//constructor
{
super("Server");
setLayout(new BorderLayout(5,5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Server Messenger"),BorderLayout.NORTH);
enteredText= new JTextField("entered message here");
enteredText.setEditable(false);
enteredText.addActionListener(new TextHandler());
add(enteredText,BorderLayout.SOUTH);
displayArea= new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public void runServer()
{
try
{
server = new ServerSocket(12345,10);//create server Socket
while(true)
{
waitForConnection();//wait util a client want to connect
openStreams();//open streams for send/get data
processConnection();//recive message from client
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void waitForConnection() throws IOException
{
displayMessage("waiting for client");
connection=server.accept();//alow server for connection
displayMessage("connect to "+connection.getInetAddress().getHostName());
}
public void openStreams() throws IOException//open stream that help me to send and recive message
{
displayMessage("setting I/O");
output= new ObjectOutputStream(connection.getOutputStream());//create output to send message
output.flush();//send headers to client
input = new ObjectInputStream(connection.getInputStream());//create input from client message
displayMessage("Got I/O");
}
public void processConnection() throws IOException//recive message from client & alow server to send message to client
{
try
{
displayMessage("connected successfully");
setTextEditable(true);//alow server to send message to client
String reciveMessage = (String)input.readObject();//recive message form client
while(!reciveMessage.equals("TERMINATE"))//if client send this string,make process connection finish
{
displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);//display clinet message in display erea
reciveMessage=(String)input.readObject();//read next message
}
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
displayMessage(connection.getInetAddress().getHostName()+" disconnect`");
close();
}
public void close() throws IOException//close every thing
{
sendMessage("TERMINATE");
input.close();
output.close();
connection.close();
setTextEditable(false);
displayMessage("connection terminated");
}
public void setTextEditable(final boolean val)//set text field editable
{
SwingUtilities.invokeLater
(
new Runnable()
{
public void run()
{
enteredText.setEditable(val);
}
}
);
}
public void displayMessage(final String message)//display message in displayArea
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
displayArea.append(message+"\n");
}
}
);
}
public void sendMessage(String message) throws IOException//send message to client
{
output.writeObject(message);
output.flush();
displayMessage("Me>>> "+message);
enteredText.setText("");
}
private class TextHandler implements ActionListener//when user press enter a text in enteredText send to client
{
public void actionPerformed(ActionEvent ev)
{
try
{
sendMessage(ev.getActionCommand());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
and it's main
//:D
public class ServerRun
{
public static void main(String[] args)
{
Server server = new Server();
server.runServer();
}
}
let's go for client code :D
//:D
//this is client side
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
public class Client extends JFrame
{
JTextField enteredText;//user input message
JTextArea displayArea;//display information
ObjectOutputStream output;//send message to server
ObjectInputStream input;//recive message from server;
Socket connection;//connection to server
String serverInfo;//server name
JButton closeB;
JPanel downPanel;
public Client ()
{
super("Client");
setLayout(new BorderLayout(5,5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Client Messenger"),BorderLayout.NORTH);
enteredText= new JTextField("Enter message Here");
setTextEditable(false);
enteredText.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
sendMessage(ev.getActionCommand());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
);
closeB= new JButton("close");
closeB.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
);
downPanel= new JPanel(new BorderLayout(5,5));
downPanel.add(enteredText,BorderLayout.CENTER);
downPanel.add(closeB,BorderLayout.EAST);
add(downPanel,BorderLayout.SOUTH);
displayArea= new JTextArea();
displayArea.setEditable(false);
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public void runClient(String host)//run client program
{
try
{
connectToServer(host);
openStreams();
processConnection();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void connectToServer(String host) throws IOException//connect to server
{
displayMessage("connceting to " + host);
connection = new Socket(InetAddress.getByName(host),12345);//create connection to server
}
public void openStreams() throws IOException // open streams for recive/send messages
{
output= new ObjectOutputStream( connection.getOutputStream());//create output for send messages
output.flush();//send headers
input = new ObjectInputStream(connection.getInputStream());//create input for recive messages
displayMessage("connected to "+connection.getInetAddress().getHostName());
}
public void processConnection()throws IOException //recive message util server trminate
{
try
{
setTextEditable(true);//alow user to send message
String reciveMessage=(String) input.readObject();
while(!reciveMessage.equals("TERMINATE"))
{
displayMessage(connection.getInetAddress().getHostName()+">>> "+reciveMessage);
reciveMessage=(String)input.readObject();
}
displayMessage("connection lost");
}
catch(ClassNotFoundException cnfe)
{
displayMessage("server message is not clear");
}
}
public void close() throws IOException//close every thing
{
sendMessage("TERMINATE");
input.close();
output.close();
connection.close();
System.exit(0);
}
public void sendMessage(String message) throws IOException//send message to server
{
output.writeObject(message);//send message to server
output.flush();//send headers
displayMessage("Me>>> "+message);//displate sent message to user
enteredText.setText("");
}
public void displayMessage(final String message)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
displayArea.append(message+"\n");
}
}
);
}
public void setTextEditable(final boolean val)
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
enteredText.setEditable(val);
}
}
);
}
}
and it's main :
//:D
import javax.swing.JOptionPane;
public class ClientRun
{
public static void main(String args[])
{
Client client = new Client();
client.runClient(JOptionPane.showInputDialog(null,"please enter host IP:"));
}
}
again thanks
Preface: This is most likely not a problem with your code, but rather a problem with your network setup. (Looks like #dimoniy beat me to answering, hopefully this sends the same idea as his).
The most likely reason that your friend cannot connect to your server is because he cannot get through your modem. In order for someone to connect to your server (from the code the port looks to be 12345) you need to change some settings in your router/modem (Which you can usually connect to by going to 192.168.1.1 or 192.168.0.1) and adding a "Port forwarding rule". This will allow connections "outside" of your network (aka the rest of the world) to connect to the server on that port.
You will need to add a 'Port Forwarding' rule to your modem/router that redirects all the traffic on port 12345 to the local ip of where you are hosting the server (your computers ip; found by ipconfig or ifconfig cmd in console/terminal). Then you will need to get your 'External IP' which can be found by Googling "what's my ip". This is the "address" of your network to the rest of the world. This is the IP that you need to give to your friend.
Your friend needs to use your External IP that you gave him, along with the port that the server is running on, and your router should forward his connection to your server and should work!
Some topics you might want research some more are: "external IP vs internal IP" and "Port Forwarding".
Hope this helps!
The problem is that you're trying to access a computer which does not have a public IP. The only thing that has "real" IP address is your router or cable modem (depending on the configuration). In order for remote computer to access the computer where the server is running you best option would be to set up port forwarding for the server port that you use (12345) and make sure that the traffic gets redirected to your machine.
The ways to set up port forwarding are different for different routers, you'll have to google your router and phrase "port forwarding".
Once everything set up the client will have to use the router's public IP address (you can look this up in your router settings). Then it will go like this: client will hit the router, router will forward the traffic to your local computer and your server socket then should do it's thing. Once the connection is established you should be good to go.
Hope that helps.