New Socket("IP" , 4444)

I wrote a simple chat program, using Sockets, now on my Client program when I create the new Socket I run into errors...
First of I must let you know that I am on a wireless connection set up in my house, therefore I am not directly connected to the internet, and I belive I have 2 ip adresses, one is assigned by my router and the other one is my TRUE internet IP...
Now if I sent this client program to a friend and I still had my router IP in the source file, it didnt work, of course not so I told him to change it to my TRUE internet IP, which he did and now it worsk just fine....
so now i continue developing, and ofcourse I change the IP to my TRUE internet IP, but now the Client program cannot connect the server if they run on the same mashine...
There fore I need my router adress when i run both (Server and Client) programs on my pc, however I need the other IP when I sent the file to a far away friend....
My question is WHY????
thanks alot guys

If I understood you correctly:
a.) You have created a client program to connect to a server on your system
b.) You have a router/firewall and a local area network, probably 192.168.1.XXX.
c.) The client program connects to the DHCP obtained wireless network address for your local
area network, and works internally--- but you for some reason must use the IP address of your router in order to access the server via an external source.
As far as I can tell, this isn't normal behavior, so something isn't quite correct about how you believe everything is working.
Lets say, for instance, your IP address was 192.168.1.100 for your local area network.
To the LAN, your router is a completely different machine, there are internal to it settings by which you can set up port forwarding. When somebody connects to it from a WAN, usually there will be a table of IP addresses of computers on the local area network associated with a particular port.
Basically, "If the firewall/router gets a packet for port 4444, then forward it to 192.168.1.100 on port 4444."
What I find strange is, unless this port forwarding has been set up, your friend should not be able to connect to your server program by proxy through your router.
If you have this proxy connection set up, essentially what will happen internally to the firewall is:
a.) Your computer will forge a packet for the desired WAN IP address (The IP of your router), and fork it off onto the network.
b.) The router will obtain the packet, realize the WAN network address is its own, and it will then check its routing tables for the specific port 4444 and find your local area network address associated with it.
c.) It should finally send that packet back to your machine on port 4444.
I really would need more information about what exactly is going on to determine what is happening.
-Jason Thomas.

Similar Messages

  • New Socket takes too long / how to stop a Thread ?

    Hello to everyone,
    I have a problem that I have been hunting this ol' Sun website all day for a suitable answer, and have found people who have asked this same question and not gotten answers. Finally, with but a shred of hope left, I post...
    My really short version:
    A call to the Socket(InetAddress,int) constructor can take a very long time before it times out. How to limit the wait?
    My really detailed version:
    I have a GUI for which the user enters comm parameters, then the program does some I/O while the user waits (but there is a Cancel button for the Impatient), then the results are displayed. Here is quick pseudocode (which, by the way, worked great before there were Sockets in this program -- only serial ports):
    Main (GUI) thread:
         --> reset the stop request flag
         --> calls workerThread.start(), then brings up a Cancel dialog with a Cancel button (thus going to sleep)
         --> (awake by dialog closing -- dialog may have been closed by workerThread or by user)
         --> set stop request flag that worker thread checks (in case he's still alive)
         --> call workerThread.interrupt() (in case he's alive but asleep for some reason (???))
         --> call workerThread.join() to wait for worker thread to be dead (nothing to wait for if he's dead already)
         --> display worker thread's result data or "Cancelled..." information, whichever worker thread has set
    Worker thread:
         --> yield (to give main thread a chance to get the Cancel Dialog showing)
         --> do job, checking (every few code lines) that stop request flag is not set
         --> if stop request, stop and set cancelled flag for Main thread to handle
         --> if finish with no stop request, set result data for Main thread to handle
         --> take down Cancel Dialog (does nothing if not still up, takes down and wakes main thread if still up)
    THE PROBLEM: Worker thread's job involves doing IO, and it may need to instantiate a new Socket. If it is attempting to instantiate Socket with bad arguments, it can get stuck... The port int is hardcoded by the program, but the IPAddress must be typed by user.
    If the arguments to Socket(InetAddress, int) constructor contain a valid-but-not-in-use IP address, the worker thread will get stuck in the Socket constructor for a LONG time (I observed 1m:38s). There is nothing the Main thread can do to stop this wait?
    EVEN WORSE: If the user clicks the Cancel Button during this time, the dialog goes away soon/immediately, but then the GUI appears to be hanging (single-threaded look) until the long wait is over (after which the "Cancelled..." info is displayed).
    MY QUESTION: Is there nothing the Main thread can do to stop this wait?
    Your answers will be sincerely appreciated. Despite my hopeless attitude (see above), the folks at this forum really have yet to let me down ...
    /Mel

    http://developer.java.sun.com/developer/technicalArticles/Networking/timeouts/

  • A new socket for every http-request?

    Do I have to make a new socket for every http-request? The code below doesn't work because it is two requests in a row. The first GET works, but the second doesn't. I thought that the purpose of a socket is that you set it up once and then you should be able to do arbitrary communication between the two peers. Maybe that is just the case with sockets only but not if you use sockets to perform http.
    Thank you for your answers! Nice greetings from Austria (not Australia)!
    Stefan :)
    package httptest;
    import javax.net.ssl.*;
    import java.io.*;
    import java.net.*;
    public class Conn2 {
        private PrintWriter out;
        private BufferedReader in;
        private Socket socket;
        public Conn2()
            try {
             socket = new Socket("www.google.at", 80);
             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));         
             if (out.checkError())
              System.out.println("SSLSocketClient:  java.io.PrintWriter error");
             in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println("Connect erfolgreich.");
         } catch (Exception e) {
             System.err.println(e);
        public void test()
            String inputLine;
            // 1. GET
            out.println("GET / HTTP/1.0");
         out.println();
         out.flush();
         try
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
            catch(IOException e)
                System.err.println(e);
            // 2. GET
            out.println("GET / HTTP/1.0");
         out.println();
         out.flush();
            try
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
            catch(IOException e)
                System.err.println(e);
    }

    Normally in the HTTP protocol, the server will close the connection after every request. So after you do the first GET, the server sends you the result and closes the connection. You have to open a new connection for the second GET.
    You can set specific headers to keep the connection open, which makes things faster if you have to do multiple GET's quickly after another. Lookup the specification of the HTTP protocol on http://www.ietf.org/
    Maybe it's easier to use a HTTP client library like Apache's HTTPClient: http://jakarta.apache.org/commons/httpclient/ so that you don't have to implement all the difficulties of the HTTP protocol yourself.

  • Using new Socket( host, port );

    how long does it take for a client to connect to the server.. How long does
    socket = new Socket( host port);
    take?
    I ask because if it takes longer on some computers, my clients wont connect in the correct order..
    Example:
    Client1 is sent to the server then
    Client2 is sent to the server then
    Client3 is sent to the server..
    Client1 takes 4 seconds to connect..
    Client2 takes 1 second!
    Client3 takes 1 second.
    In this case client's 2 and 3 with get in before client1 but I want them to connect in the correct order? Do I need to worry about new Socket( host, port ) load times or are they negligible?

    How long it takes depends on a lot of things - for example, on the network traffic. It's in general impossible to predict.
    Why does your program require that the clients connect in a certain order?
    If you really have to make sure that clients connect in a certain order, then you'll have to invent a mechanism to insure this yourself. For example, first tell client 1 to connect and wait for the connection to be established, then tell client 2 to connect and wait, etc.

  • New Socket() acting strangely under Windows

    Hello,
    First a little background:
    I have a client application that connects to a server application through a socket. The client first checks to see the server is 'reachable' using the .isReachable() method. If this return true, all is good. If it returns false, the application sets up to use a Microsoft Windows DUN connection and VPN to connect to the server. This is handled through a 3rd party .jar file called jdialup. Oh, one more thing, the client pc is connected to the network through a hub. In other words, the pc is connected to a hub. The hub is connected to the network using it's up-link port... Everything so far is pretty simple enough...
    Now the issue:
    If I disconnect the network cable from the back of the pc and run my client application, it says that the server is not reachable, which is fine. The application then dials out to our ISP and connects to our VPN. The client application connects to the server application through a socket and sends the request and receives the response. The client then disconnects. Everything is GOOD.
    Now, if I disconnect the network cable from the up-link on the hub, thus removing the client pc from the network, this is where the strangeness happens! I run my client application, it again says that the server is not reachable, which is fine. The application again dials out to our ISP and connects to our VPN. This is fine. Now though, when I attempt to make the socket connection to the server, it times out! The actual call to
    Socket socket = new Socket(ipaddress, port);times out...
    This seems very strange to me... Any ideas?
    PS: In both situations when I connect to the VPN, I can ping and telnet to the server. It is the Socket call that is acting strange...
    Thanks,

    I've been following this and I'm baffled by the
    discussion so far. Has the thread been trimmed? I believe we got off on a tangent, but the problem is that in certain circumstances the client application tries to connect to the server application the call the 'new Socket()' times out... You will have to read my original post...
    Anyway, I believe that I have figured it out. It was related to the gateway option in the network setup on the client pc.
    Originally I had the gateway option set to be an ip address internal to our network. Our network guy said that in this situation, I needed to set the gateway to an ip address outside out network. When I did that, everything now work beautifully. Why? I have no real idea as I am not a network guy, but it work now and I am happy...
    Thanks for everyones help and sorry for all the confusion.

  • Missing Active/New Sockets during SSL Setup

    Hello Everyone,
    We have a situation where we tried to upload a new signed SSL cert ( the previous one worked fine ).
    After uploading the new cert; we have lost the SSL port (5XX01) under Active/New Sockets in VA
    Anyone know what would cause this?

    Thanks..
    How do you re-add the ports? We didn't change anything to begin with.
    Anyways, we removed the signed cert and bounced the system. The ports came back and everything worked.

  • New to sockets. How to implement multithreaded servers?

    I have been reading the JAVA tutorial, but can't get a simple "echo" threaded server working here:
    EchoServerThread.java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    public class EchoServerThread extends Thread{
         private Socket s;
         public EchoServerThread(Socket socket){
              super("EchoServerThread");
              this.s=socket;
         public void run(){
              try {
                   PrintWriter out = new PrintWriter(s.getOutputStream(),true);
                   BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                   String rline;
                   while((rline=in.readLine())!=null){
                        /*if(rline.equalsIgnoreCase("exit")) {
                             out.println("exit");
                             break;
                        out.println(rline);
                   in.close();
                   out.close();
                   s.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }EchoServer.java
    import java.io.IOException;
    import java.net.ServerSocket;
    public class EchoServer {
         public static void main(String[] args) {
                   ServerSocket ssoc = null;
                   try {
                        ssoc = new ServerSocket(4444);
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   while(true)
                        try {
                             new EchoServerThread(ssoc.accept()).run();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
    }EchoClient.java
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class EchoClient {
         public static void main (String [] args){
              try {
                   Socket soc = new Socket("localhost",4444);
                   PrintWriter out = new PrintWriter(soc.getOutputStream(),true);
                   BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
                   BufferedReader stdIn= new BufferedReader(new InputStreamReader(System.in));
                   String rline;
                   while((rline=stdIn.readLine())!=null){
                        out.println(rline);
                        //System.out.println("written: "+rline);
                        /*String fromServer = in.readLine();
                        if(fromServer.equals("exit")){
                             System.out.println("Server is going down....");
                             System.out.println("fuck");
                             break;
                        else{*/
                        System.out.println("echo: "+in.readLine());
                   in.close();
                   out.close();
                   stdIn.close();
                   soc.close();
              } catch (UnknownHostException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   System.exit(1);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   System.exit(2);
    }What happens, is that the server only accepts another connection after a client dies. If I do some input on the 2nd opened client ( the 1st is still beeing served) it produces no output until the 1st one ends, then it produces all the correct output.

    Hi,
    it's just an idea that has come to my mind rigth now while eating my pizza, probably a big mistake. You could try to flush the BufferedReader cause maybe it remains blocked in this while((rline=in.readLine())!=null){
         /*if(rline.equalsIgnoreCase("exit")) {
              out.println("exit");
              break;
         out.println(rline);
    }while loop. Just an idea though, probably it's wrong!
    JoY?TiCk

  • A beginner in socket programming

    Ok I am been stuck on this program for the whole day trying to figure out why I cannot connect to my server computer using sockets and threads.
    I am trying to implement a instant messenger program where each user acts has both client/server. Each client creates a listening socket and all use a common port number, (in this case port 4444).
    If client 1 wants to interact with client 2, client 1 query�s my MySQL database for their status. Now if their status is online, retrieve their current ip address. So far so good. My program does not with no problem.
    Now comes the painful part. Now that client 1 knows client 2 is online and has his/hers ip, the next step is to connect to client 2�s listening socket using their ip and the port number 4444. Now after connecting to that socket, a new chat dialog gui is suppose to open from the client 2�s side. This new chat dialog gui (jframe) is a thread so that if other users wishes to interact with client 2, another new chat dialog thread will appear!
    But in my case nope! Has soon as client 1 tries to establish a connection with client 2, boom. Error, connection refused: connect!!
    Now I been searching through Google trying to understand what this means and so far I found null� now I posted before asking what that means and someone told me it means that I forgot to close the sockets and input, output streams. But how can I close it when I cannot even establish a connection with client 2??
    Things I have tried:
    I tried inputting myself, the actual ip of client 2 and guess what� no luck
    I tried the client 2�s computer name, and same thing!
    I tried to create a whole new main class just so that I can open and close the sockets and input/output stream and nope, no luck at all..
    Now that you have a good understanding of my program. Here comes the code:
    I�l start with the user_window, which is the main menu as you call it: this jframe once opened, is suppose to create a server socket to listen for connections. If a connection is made, load the chatdialog gui thread�
    * user_window.java
    * Created on 10 February 2006, 11:50
    package icomm;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    * @author jonathan
    public class user_window extends javax.swing.JFrame implements WindowListener {
    protected String crnt_user;
    protected String crnt_ip;
    protected String dummy = "";
    /** Creates new form user_window */
    public user_window() {
    initComponents();
    listeningSocket();
    addWindowListener( this );
    public user_window(String users_name)
    initComponents();
    addWindowListener( this );
    this.crnt_user = users_name;
    private void exit()
    MySQL_queries offline = new MySQL_queries();
    offline.off_status(crnt_user);
    JOptionPane.showMessageDialog(null, "you are about to close the program " + crnt_user, null, JOptionPane.ERROR_MESSAGE);
    MySQL_queries query = new MySQL_queries();
    query.off_status(crnt_user);
    query.reset_ip(crnt_user);
    System.exit(0);
    public void windowClosing(WindowEvent e)
         exit();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    try {
    Buddie_list =(javax.swing.JTree)java.beans.Beans.instantiate(getClass().getClassLoader(), "icomm.user_window_Buddie_list");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    label = new javax.swing.JLabel();
    demo = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Close = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();
    profile = new javax.swing.JMenuItem();
    jMenu3 = new javax.swing.JMenu();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().add(Buddie_list, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 230, 310));
    getContentPane().add(label, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
    demo.setText("talk to shienna");
    demo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    demoActionPerformed(evt);
    getContentPane().add(demo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1));
    jMenu1.setText("File");
    jMenu1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenu1ActionPerformed(evt);
    Close.setLabel("Close");
    Close.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CloseActionPerformed(evt);
    jMenu1.add(Close);
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Option");
    profile.setText("Edit Profile");
    profile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    profileActionPerformed(evt);
    jMenu2.add(profile);
    jMenuBar1.add(jMenu2);
    jMenu3.setText("Help");
    jMenuBar1.add(jMenu3);
    setJMenuBar(jMenuBar1);
    pack();
    // </editor-fold>
    private void demoActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    ChatDialog_c chatting = new ChatDialog_c(crnt_user, dummy);
    chatting.setTitle("I-comm");
    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chatting.setSize(360, 500);
    chatting.getSize();
    chatting.setLocation(420,200);
    chatting.setVisible(true);
    private void CloseActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void demo1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void show_chat_window()
    ChatDialog chat_gui = new ChatDialog();
    chat_gui.setTitle("chat");
    chat_gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chat_gui.setSize(366, 480);
    chat_gui.getSize();
    chat_gui.setLocation(420,200);
    chat_gui.setVisible(true);// TODO add your handling code here:
    private void log_offActionPerformed(java.awt.event.ActionEvent evt) {                                       
    private void locate_ip()
    try
    InetAddress a;
    a = InetAddress.getLocalHost(); //get ip addrees
    this.crnt_ip = a.getHostAddress(); //then store it in this variable
    catch(UnknownHostException e)
    JOptionPane.showMessageDialog(null, "Error, cant detect localhost", null, JOptionPane.ERROR_MESSAGE);
    public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e)
    locate_ip();
    MySQL_queries new_ip = new MySQL_queries();
    new_ip.update_ip(crnt_user, crnt_ip);
    JOptionPane.showMessageDialog(null,"hello " + crnt_user + " your ip is" + crnt_ip, null, JOptionPane.ERROR_MESSAGE);
    private void listeningSocket()
    ServerSocket serverSocket = null;
    boolean listening = true;
    try
    //listen in port 4444;
    serverSocket = new ServerSocket(4444);
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
    while(listening)
    try
    ChatDialog chat = new ChatDialog(serverSocket.accept());
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "could not open chat window", null, JOptionPane.ERROR_MESSAGE);
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    private void profileActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new user_window().setVisible(true);
    Now for the chatdialog class: I forgot to mention that I have two versions of this class. One that is a thread and the other makes a connection to a thread, hope that makes sence�
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog_c extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket socket = null;
        protected String ip2;
        private PrintWriter out = null;
        private BufferedReader in = null;
        private String user_name;
        private String status;
        /** Creates new form ChatDialog_c */
        public ChatDialog_c()
            initComponents();
            addWindowListener( this );
         public ChatDialog_c(String ip1)
            initComponents();
            addWindowListener( this );
            this.ip2 = ip1;
            //OptionPane.showMessageDialog(null, "error in closing sockdswdset " + ip2, null, JOptionPane.ERROR_MESSAGE);
         public ChatDialog_c(String user, String status)
            initComponents();
            addWindowListener( this );
            this.user_name = user;
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {
                try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
              MySQL_queries get_ip = new MySQL_queries();
              this.ip2 = get_ip.find_client(user_name);
               JOptionPane.showMessageDialog(null, user_name + ip2, null, JOptionPane.ERROR_MESSAGE);
                //create socket connection
                try
                    socket = new Socket ("Shienna", 4444);
                    out = new PrintWriter(socket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                catch(UnknownHostException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "unknown  " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "2 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
                 try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                while(true)
                    try
                        String line = in.readLine();
                        convo_txt.append(line);
                    catch(IOException x)
                        x.printStackTrace();
                        JOptionPane.showMessageDialog(null, "3 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 280));
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 220, 70));
            send.setText("Send");
            send.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendActionPerformed(evt);
            getContentPane().add(send, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, -1, -1));
            jMenu1.setText("File");
            jMenu1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu1ActionPerformed(evt);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Option");
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>                       
        private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                    
            String text = txt_messege.getText();
            out.println();
            txt_messege.setText(new String(""));
            convo_txt.append(text);
        private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog_c().setVisible(true);
        }///////////////////////chat dialog thread/////////////////////
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener, Runnable {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        public ChatDialog(String txt_messege)
            initComponents();
            addWindowListener( this );
            this.messege = txt_messege;
         public ChatDialog(Socket user)
             initComponents();
             addWindowListener( this );
             this.client_user = user;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured ";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                   //send data back to user
                   out.println(messege);
                   //append data on the text field
                   convo_txt.append(messege + "\n");
                   //chat_gui.setVisible(true);
                   //-=inputs = new ChatDialog(messege);
               //out.close();
                //in.close();
                //client_user.close();
            catch (IOException e)
                //error messege
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, error + e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }If I can sort this problem out I would of completed the main part of my program. I have spent days on this and hope that anyone of you guys can take the time out and help me with my current situation. Thanks

    update:
    i have managed to sort out the connection refused
    i know have anotehr problem: both client2 program freezes as soon as client 1 tries to initiate a connection to client 2!!!!!!!!
    when client 2 logs into teh system. it freezes as soon as i press the button! but when client 1 attempts to conenct to client 2, client 2's program stops freezing and the chatdialog comes up showing nothing and freezes! my chadialog is suppose to show a file menu i made but it doesnt,. both clients freezes at this point. no error messeges occur...

  • Problem in socket communication please help me!

    server
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
         JLabel text1, text2;
         JButton button1, button2;
         JPanel panel;
         JTextField textField1, textField2;
    ServerSocket server = null;
    Socket socket = null;
    BufferedReader in1 = null;
    PrintWriter out1 = null;
    String line1;
    String line2;
    SocketServer(){ //Begin Constructor
              text1 = new JLabel("Send Information:");
              text2 = new JLabel("Receive Information:");
              textField1 = new JTextField(20);
              textField2 = new JTextField(20);
              button1 = new JButton("Send");
              button2 = new JButton("Receive");
              button1.addActionListener(this);
              button2.addActionListener(this);
              panel = new JPanel();
              panel.setLayout(new GridLayout(2,3));
              panel.setBackground(Color.lightGray);
              getContentPane().add(panel);
              panel.add(text1);
              panel.add(textField1);
              panel.add(button1);
              panel.add(text2);
              panel.add(textField2);
              panel.add(button2);
              setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event) {
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out1.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line1 = in1.readLine();
                        System.out.println("Text received :" + line1);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line2);
         public void listenSocket(){
              try{
                   server = new ServerSocket(4444);
              } catch (IOException e) {
                   System.out.println("Could not listen on port 4444");
                   System.exit(-1);
              try{
                   socket = server.accept();
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              try{
                   in1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   out1 = new PrintWriter(socket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println("Accept failed: 4444");
                   System.exit(-1);
              while(true){
                   try{
                        line2 = in1.readLine();
                        //Send data back to client
                        out1.println(line2);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         protected void finalize(){
              //Clean up
              try{
                   in1.close();
                   out1.close();
                   server.close();
              } catch (IOException e) {
                   System.out.println("Could not close.");
                   System.exit(-1);
         public static void main(String[] args){
              SocketServer frame = new SocketServer();
              frame.setTitle("Chat (Server)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    client
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text1, text2;
    JButton button1, button2;
    JPanel panel;
    JTextField textField1, textField2;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String line3;
    String line4;
    SocketClient(){ //Begin Constructor
    text1 = new JLabel("Send Information:");
         text2 = new JLabel("Receive Information:");
    textField1 = new JTextField(20);
         textField2 = new JTextField(20);
    button1 = new JButton("Send");
         button2 = new JButton("Receive");
    button1.addActionListener(this);
         button2.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new GridLayout(2,3));
    panel.setBackground(Color.lightGray);
    getContentPane().add(panel);
    panel.add(text1);
    panel.add(textField1);
    panel.add(button1);
         panel.add(text2);
         panel.add(textField2);
         panel.add(button2);
         setSize(500,100);
    } //End Constructor
         public void actionPerformed(ActionEvent event){
              Object source = event.getSource();
              if(source == button1){
                   //Send data over socket
                   String text = textField1.getText();
                   out.println(text);
                   textField1.setText(new String(""));
                   //Receive text from server
                   try{
                        String line3 = in.readLine();
                        System.out.println("Text received :" + line3);
                   } catch (IOException e){
                        System.out.println("Read failed");
                        System.exit(1);
              if(source == button2){
                   textField2.setText(line4);
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("Localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: Localhost");
                   System.exit(1);
              } catch (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
              while(true){
                   try{
                        line4 = in.readLine();
                        //Send data back to client
                        out.println(line4);
                   } catch (IOException e) {
                        System.out.println("Read failed");
                        System.exit(-1);
         public static void main(String[] args){
              SocketClient frame = new SocketClient();
              frame.setTitle("Chat (Client)");
              WindowListener l = new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              frame.addWindowListener(l);
              frame.pack();
              frame.setVisible(true);
              frame.listenSocket();
    There were problems when executing the application
    please help me

    i had no problem running this... make sure you open the server part first and have that sitting and waiting for the client to connect.... then it should work.
    Would you believe that i too am working on the server / socket thing... however my problem is getting the server to read from a database and report back to the client....

  • Applet - Server socket problem

    Hello i'm trying to develop a simple chat application
    The applet connects to the server via a socket and it can successfully send a line of text to the server and receive one back.
    But if I try to put a loop in to receive more lines the applet doesn't start
    here is some source, i'd appreciate any help
    * ChatClient.java
    * Java Applet for communicating with server
    import java.io.*;
    import java.net.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ChatClient extends Applet
         public Panel input;
         public OutputPanel output;
         public PrintWriter out = null;
    public BufferedReader in = null;
         public Socket client = null;
         public Label label;
         public TextField itext;     
         public boolean connected = false;
         public String fromServer = "";
         public void init()
              setLayout( new BorderLayout() );
              input = new Panel();
              input.setLayout( new FlowLayout() );
              label = new Label( "Enter Message" );
              itext = new TextField( 15 );
              TextHandler handler = new TextHandler();
              itext.addActionListener( handler );
              input.add( label );
              input.add( itext );          
              output = new OutputPanel();     
              add( "South", input );
              add( "Center", output );
         public void start()
              String host = getDocumentBase().getHost();          
              try
                   // create socket connection
                   client = new Socket( host, 4444 );
                   out = new PrintWriter( client.getOutputStream(), true );
    in = new BufferedReader( new InputStreamReader( client.getInputStream() ) );
              catch (UnknownHostException e)
                   System.err.println("Don't know about host: 10.1.7.2.");
    System.exit(1);
              catch (IOException e)
    System.err.println("Couldn't get I/O for the connection to: 10.1.7.2.");
    System.exit(1);
              output.otext.append( "Chat client started, listening\n\n" );
              listen();               
         public void listen()
              out.println( "Client 1" );
              try
                   fromServer = in.readLine();
                   output.otext.append( "Server: " + fromServer + "\n\n" );
                   connected = true;
                   //do
                   //     fromServer = in.readLine();
                        System.err.println( "Server: " + fromServer );
                   //     if ( fromServer.equals( "Bye" ) )
                   //          connected = false;
                   //     output.otext.append( "Server: " + fromServer + "\n\n" );
                   //}while ( connected );
              catch( IOException io )
                   System.err.println( "Cannot read from server" );
                   io.printStackTrace();
         public void sendData ( String s )
              out.println( s );
              //output.otext.append( "Client: " + s + "\n\n" );
         public void destroy()
              try
                   out.println( "Bye" );
                   out.close();
                   in.close();
                   client.close();
              catch( IOException io )
                   System.err.println( "Error closing Socket or IO streams");
                   io.printStackTrace();
    class TextHandler implements ActionListener
         public void actionPerformed( ActionEvent e )
              sendData( e.getActionCommand() );
    public String getAppletInfo()
              return "A simple chat program.";
         public static void main(String [] args)
              Frame f = new Frame( "Chat Applet" );
              ChatClient chatclient = new ChatClient();
              chatclient.init();
              chatclient.start();          
              f.add( "Center", chatclient );
              f.setSize( 300, 300 );
              f.show();
    class OutputPanel extends Panel
         public TextArea otext;
         public OutputPanel()
              setBackground( Color.white );
              setLayout( new BorderLayout() );
              otext = new TextArea( 6, 60 );
              otext.setEditable( false );
              add( "Center", otext );
              setVisible( true );
    public void paint(Graphics g)
    }

    I think you have to modify the loop, which receive data from your socket.
    here an example which I tryed
    hope I can help you
    while (z==1)
    anzeige = in.readLine();
    if (anzeige.charAt(0) == ende.charAt(0) && anzeige.charAt(1) == ende.charAt(1) && anzeige.charAt(2) == ende.charAt(2)) // searching for the end"-~-"
    break;
    textField.add(anzeige);

  • Socket error.How do I fix this

    Hello all,
    I tried running this cleint server program that I built.This is the error I get.How do I fix this.
    The exception in thread isjava.net.SocketException: Software caused connection abort: recv failed
    Code is posted below.
    Thanks.
    Regards.
    nitin.p
    Clent code
    try{
           Socket ClientSocket=new Socket("localhost",4444);
          ObjectOutputStream out=new ObjectOutputStream(ClientSocket.getOutputStream());
          out.writeObject(p);
          out.flush();
          out.close();
          Object incoming_info;
          ObjectInputStream in=new ObjectInputStream(ClientSocket.getInputStream());
          incoming_info=in.readObject();
          System.out.println("Incoming info"+incoming_info);
          in.close();
       ClientSocket.close();
        }Server code
    package ajp;
    import java.net.*;
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.sql.*;
    public class agpt extends Thread
      private Socket clSocket;
      private String id;
      private byte[] passwd;
      public agpt(Socket clientSocket)
        clSocket = clientSocket;
      public void run()
        try
          ObjectInputStream in = null;
          in = new ObjectInputStream(clSocket.getInputStream());
           ObjectOutputStream out = null;
           out = new ObjectOutputStream(clSocket.getOutputStream());
          Object zz="dkjsdkjsdksdj";
          out.flush();
          String res = "";
          //ObjectOutputStream out = null;
          //out = new ObjectOutputStream(clSocket.getOutputStream());
          Object temp = in.readObject();
         // in.close();
          System.out.println("I am in thread");
          String operation = ( (Protocol) temp).get_operation_name();
          System.out.println(operation);
                statement.executeUpdate("CREATE TABLE TABLE1 (" +
                                 "Username   VARCHAR (20)  NOT NULL, " +
                                   "Password   VARCHAR (20) NOT NULL, " +
                                 "PRIMARY KEY( Username)" + ")");
          if (operation.equals("register"))
            id = ( (Protocol) temp).get_user_id();
            System.out.println("Id is" + id);
            passwd = ( (Protocol) temp).get_user_password();
            System.out.println("paxxwd" + passwd);
            String original = new String("UTF8");
            original = passwd.toString();
            Protocol pmess = new Protocol();
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection conn = DriverManager.getConnection("jdbc:odbc:mage");
            Statement statement = conn.createStatement(ResultSet.
              TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            System.out.println("*****");
            ResultSet result = statement.executeQuery("SELECT * FROM TABLE1");
            while (result.next())
              if (result.getString("Username").compareTo(id) == 0)
                pmess.set_message("ID already exists please enter new");
            if (res.equals(""))
              PreparedStatement stmt = conn.prepareStatement(
                "INSERT INTO TABLE1 VALUES(?,?)");
              stmt.setString(1, id);
              stmt.setString(2, original);
              stmt.executeUpdate();
              System.out.println("I am in res");
              pmess.set_message("Registration done successfully");
            result.close();
            statement.close();
    System.out.println("I reached here");
            out.writeObject(zz);
            out.close();
            in.close();
             conn.close();
            clSocket.close();
        catch (Exception e)
          System.out.println("The exception in thread is" + e);

    in the client codes, try closing the output stream later, after in.readObject()

  • Cannot establish a socket

    Hi I have written an applet which I have displayed on my homepage, its a registration form that I had hoped to use to allow people to create acounts for a program (im very slowly) working on.
    When the register button on the applet is clicked, a socket is created on a server ive also written which runs on my pc and the specified username and password are sent to a server and recorded.
    Problem is I cant get the applet to estabilish a socket when I try viewing my homepage from outside of my network.
    Just to clear a few things up!
    Im running my own web server Apache 2.0.
    Its not a software or hardware firewall issue I have all nessary ports forwarded to my router correctly. I have successfully connected to the server from a client that isnt an applet in a webpage from outside my network.
    Is this a Java security issue where by an applet cant estabilish a socket on a server ?

    Ok heres a simplified version of my code!
    Incase theres any confussion to test this you will need to save all 4 of the following files into the same directory.
    ServerThread, Server and Applet as .java files and then compile them.
    Applet.html as a html file.
    Run the Server and then open index.html in a web browser.
    Applet Code Applet.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.Socket;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Scanner;
    import java.io.PrintWriter;
    import java.io.*;
    public class Applet extends JApplet
        static JTextField inputFieldUsername;
        static JLabel labelUsername;
        static JButton buttonRegister;
        static JLabel labelServerError1;    
        static Socket skt;
        static Scanner in;
        static PrintWriter out;
        static InputStream instream;
        static OutputStream outstream;
        public void init()
             try
                 skt = new Socket("localhost", 4444);
                 instream = skt.getInputStream();
                 outstream = skt.getOutputStream();
                 in = new Scanner(instream);
                 out = new PrintWriter(outstream);
                 setLayout(null);
                 setSize(200, 300);
                  labelUsername = new JLabel("Username:");
                  getContentPane().add(labelUsername);
                  labelUsername.setBounds(30, 50, 100, 20);
                  inputFieldUsername = new JTextField();
                  getContentPane().add(inputFieldUsername);
                  inputFieldUsername.setBounds(140, 50, 200, 20);
                  buttonRegister = new JButton("Register");
                  getContentPane().add(buttonRegister);
                  buttonRegister.setBounds(155, 200, 90, 20);
             catch(Exception ex)
                 setLayout(null);
                 setSize(200, 300);        
                 labelServerError1 = new JLabel("<html><body><p>Server is temporarily down, please refresh your web browser.</p></body></html>");
                 getContentPane().add(labelServerError1);
                 labelServerError1.setBounds(140, 30, 200, 50);
    }  Server Code Server.java
    import java.net.*;
    import java.io.*;
    public class Server
        public static void main(String[] args) throws IOException
            ServerSocket serverSocket = null;
            boolean listening = true;
            try
                serverSocket = new ServerSocket(4444);
                System.out.println("Server enitilized, awating clients.");
            catch (IOException e)
                System.err.println("Could not listen on port: 4444.");
                System.exit(-1);
            while (listening)
                new ServerThread(serverSocket.accept()).start();
                  System.out.println("Client connected");
            serverSocket.close();
    }Code to create individual threads for each client that connects ServerThread.java
    import java.net.*;
    import java.io.*;
    import java.util.Scanner;
    public class ServerThread extends Thread
        static InputStream instream;
        static OutputStream outstream;
        static Scanner in;
        static PrintWriter out;
        private Socket socket = null;
        public ServerThread(Socket socket)
             super("MultiServerThread");
             this.socket = socket;
        public void run()
             try
                  instream = socket.getInputStream();
                in = new Scanner(instream);
                outstream = socket.getOutputStream();
                out = new PrintWriter(outstream);
                 while(in.hasNext())
            catch (IOException e)
    }Html Code index.html
    <html>
    <body>
         <h1 align="center">Register a username</h1>
              <hr>
                         <p>Enter a username and press register to register it</p>
                 <hr>
            <applet CODE="Applet.class" WIDTH="500" HEIGHT="250"></applet>
            <hr>
    </body>
    </html>You should fine that the client is able to establish a socket on the server, but it you edit the line in Applet.java
    skt = new Socket("localhost", 4444); to skt = new Socket("Your external Ip address", 4444);
    And if your using a router you port forward 4444 on your router to the ip address of the computer on ur network running the server the client will no longer be able to establish a socket on the server.
    Why is this?
    If i havent explained my problem clearly enough please tell me and ill try rephase it!

  • Sending "System.out" to a socket

    Is it possibly to direct "System.out" to a socket. It can be done to a file with System.setOut(new PrintStream(new FileOutputStream(new File("/log.txt"))));
    Reagards
    Ulf

    Is this OK?
    import java.net.*;
    import java.util.*;
    import java.io.*;
    public class Log
    public static String host= "localhost";
    public static Socket clientSocket=null;
    public static PrintStream pstream=null;
    public static void main(String [] args) throws Exception
    clientSocket=new Socket(host,4444);
         pstream=new PrintStream(clientSocket.getOutputStream(),true);
         System.setOut(pstream);
    clientSocket.close();

  • Client Server Socket With GUI

    Hi,
    As the name of the forum suggests I am very new to this whole thing.
    I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
    I have the code for everything cept the encryption part.
    Any help, greatly appreciated,

    tnks a million but how do i incorporate that into the following client and server code:
    here's the client code:
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text, clicked;
    JButton button;
    JPanel panel;
    JTextField textField;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    SocketClient(){ //Begin Constructor
    text = new JLabel("Text to send over socket:");
    textField = new JTextField(20);
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", text);
    panel.add("Center", textField);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event){
    Object source = event.getSource();
    if(source == button){
    //Send data over socket
    String text = textField.getText();
    out.println(text);
         textField.setText(new String(""));
    //Receive text from server
    try{
         String line = in.readLine();
    System.out.println("Text received :" + line);
    } catch (IOException e){
         System.out.println("Read failed");
         System.exit(1);
    public void listenSocket(){
    //Create socket connection
    try{
    socket = new Socket("HUGHESAN", 4444);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
    System.out.println("Unknown host: HUGHESAN.eng");
    System.exit(1);
    } catch (IOException e) {
    System.out.println("No I/O");
    System.exit(1);
    public static void main(String[] args){
    SocketClient frame = new SocketClient();
         frame.setTitle("Client Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    SERVER Code
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
    JButton button;
    JLabel label = new JLabel("Text received over socket:");
    JPanel panel;
    JTextArea textArea = new JTextArea();
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;
    SocketServer(){ //Begin Constructor
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", label);
    panel.add("Center", textArea);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == button){
    textArea.setText(line);
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    try{
    client = server.accept();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    while(true){
    try{
    line = in.readLine();
    //Send data back to client
    out.println(line);
    } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
    protected void finalize(){
    //Clean up
    try{
    in.close();
    out.close();
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close.");
    System.exit(-1);
    public static void main(String[] args){
    SocketServer frame = new SocketServer();
         frame.setTitle("Server Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    Again help on this is very welcomed

  • Trouble connecting sockets...

    hi.
    i'm trying to connect to sockets over the internet but everytime i used my computers domain name when setting up the socket on the clients side they do not connect , here is the code im using:
    server
    ServerSocket serversocket = null;
    Socket clientsocket = null;
    try {
    serversocket = new ServerSocket(4444);
    clientsocket.accept();
    catch (Exception e) { }
    client
    Socket clientsocket = null;
    try {
    clientsocket = new Socket("mydomain", 4444);
    catch (Exception e) { }
    I'm testing these using the same computer and the only way it will connect is if i use my computers name which is "Craig" as the domain name but when i tested it on two computers it never worked
    ???

    here is my full source codes for my server and client progs:
    client:
    import java.net.*;
    import java.io.*;
    public class client {
    public static void main(String[] ags) {
    Socket clientsocket = null;
    try {
    clientsocket = new Socket(InetAddress.getByName(""), 6795);
    System.out.println("Connected");
    catch (Exception e) {
    System.out.println("error occured: " + e);
    server
    import java.net.*;
    import java.io.*;
    public class server {
    public static void main(String[] args) {
    ServerSocket serversocket = null;
    Socket clientsocket = null;
    try {
    serversocket = new ServerSocket(6795);
    System.out.println("Adding new socket to port 6795");
    System.out.println("waiting for client...");
    clientsocket = serversocket.accept();
    System.out.println("connected");
    catch (Exception e) {
    System.out.println("error occured: " + e);
    ???

Maybe you are looking for

  • Tecra 9100, a blue screen appears

    When I start up Novell GroupWise on my Tecra 9100 a blue screen appears? Very weird. Can anyone help me to stop this.

  • How to get more applications in the dock folder??

    Hello! I Have a MacBook Pro and an iMac. On my iMac, all the apps are in the folder on the dock but on my MBP It only has a few and I don't know how to add apps to it. Why is this?? I tried dragging apps to the folder but they don't go in. Any though

  • Using j_security_check container authentication with JSF

    Hi All, After quite a bit of looking around, we resorted to using a plain login JSP page with a ServletFilter on j_security_check to have container managed authentication in our JSF based web-site using IBM Websphere 5.1 So, basically every other pag

  • Acrobat install issue

    I am running newly installed Mavericks OS and Acrobat seems to be installed okay, but when I launch it, I get "Adobe Software License Agreement" that I can't "Accept"!

  • HOW TO IDENTIFY WINDOWS VIRUSES?

    HI, my question is;is it possible to identify windows viruses on usb stick when I open it on mac?I know that is no problem for mac but for my pc maybe. Thank you