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...

Similar Messages

  • Daemon and socket programming

    Hi,
    I have been given a new project whereby I have to:
    1) Write a class with a method that takes as an argument an xml document, communicate s with a SOAP server and return the SOAPs response (in this case a ResponseWrapper object).
    2) This then has to be implemented as a Daemon, that listens to a particular socket.
    The reason for this being is that it can be uploaded to a server, allowing a pearl program to send the XML to the Daemon, have this contact the SOAP server and then return the SOAPs response back to the pearl program.
    I am aware that this sounds unnecessarily complicated but it does have to be implemented this way.
    I have written the class and it successfully communicates with the SOAP server and returns a response, but have no idea how to implement it as a Daemon and have had no experience with socket programming.
    Could anyone point me to a tutorial or give me some pointers in how to get started?
    Thanks,

    It was an option to use a Web Service, but I was told
    that due to security issues it would take to long to
    write all the necessary checks and interceptors
    (which I know how to do), so I should implement it
    this way (which I don't know how to do); since it is
    sitting behind the firewall it would not be
    accessible for spoofing.Huh? You realize that tons of very sensitive information is transmitted all over the internet using Web Services right?
    I have had no experience
    with implementing this type of thing before, What is your level of experience then? This may be over your head. I'm not saying that sockets and daemons are advanced concepts, but I wouldn't throw a beginner into that task.

  • TCP/IP socket programming in ABAP

    Hi,
    Is there any method of TCP socket programming in ABAP? For example is there any function module for creating a socket for a IP address and port number. After that, is it possible to send binary/text data to a connected IP/port destination. I need such a solution because I need to send raw data (native commans) to barcode printer on our network which has a static IP address and listens incoming data through a fixed port number specified in its documentation. For a solution, I coded some .NET VB and built a small application that acts as a RFC server program which can be called by SAP according to definitions I made in SM59 (I defined a new TCP connection and it works well sometimes!). In this application, data coming from SAP are transferred to the barcode printer. This is achived by the .NET Socket class library. This solution works well but after a few subsequent call from SAP, connection hangs! SAP cannot call the application anymore, I test the connection in SM59 and it also hangs, so I need to restart the VB application, but this is unacceptable in our project.
    As a result, I decided to code the program that will send data to the printer in ABAP as a function module or subroutine pool, so is there any way to create a socket in ABAP and connect to specific IP/port destination? I searched for possible function modules in SE37 and possible classes in SE24 but unfortunately I could not find one. For example, do know any kind of system function in ABAP (native commands executed by CALL statement), that can be used for this purpose?
    I would appreciate any help,
    Kind regards,
    Tolga
    Edited by: Tolga Togan Duz on Dec 17, 2007 11:49 PM

    Hi,
    I doubt that there is a low level API for sockets in ABAP. There is API for HTTP but probably that won't help you. As a workaround you can use external OS commands (transactions SM69 and SM49). For example on Unix you can use netcat to transfer file. Your FM needs to dump data into folder and then call netcat to transfer file.
    Cheers

  • File descriptor leak in socket programming

    We have a complex socket programming client package in java using java.nio (Selectors, Selectable channel).
    We use the package to connect to a server.
    Whenever the server is down, it tries to reconnect to the server again at regular intervals.
    In that case, the number of open file descriptors build up with each try. I am able to cofirm this using "pfile <pid>" command.
    But, it looks like we are closing the channels, selectors and the sockets properly when it fails to connect to the server.
    So we are unable to find the coding that causes the issue.
    We run this program in solaris.
    Is there a tool to track down the code that leaks the file descriptor.
    Thanks.

    Don't close the selector. There is a selector leak. Just close the socket channel. As this is a client you should then also call selector.selctNow() to have the close take final effect. Otherwise there is also a socket leak.

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Network and socket programming in python

    i want to learn network and socket programming but i would like to do this in python.Reason behind this is that python is very simple and the only language i know . 
    anybody can suggest me which book should i pick.
    the book should have following specification--
    1)not tedious to follow
    2)lots of example
    3)starts with some networking stuff and then get into codes
    thanks in advance with regards.

    hmm. well, your requirements are almost contradictory.
    Not sure about books, except maybe dusty's.
    Most python books cover at least some network programming (unless the book is topic specific).
    I use lots of python-twisted at work. I mean ALOT. I wouldn't recommend it to someone looking for non-tedious though! I also like gevent/eventlet (esp. the async socket wrappers).
    EDIT: Wow. My post wasn't really helpful at all. Sorry!
    Last edited by cactus (2010-09-04 09:16:54)

  • Socket Programing in J2ME - Confused with Sun Sample Code

    Hai Everybody,
    I have confused with sample code provided by Sun Inc , for the demo of socket programming in J2ME. I found the code in the API specification of J2ME. The code look like :-
    // Create the server listening socket for port 1234
    ServerSocketConnection scn =(ServerSocketConnection) Connector.open("socket://:1234");
    where Connector.open() method return an interface Connection which is the base interface of ServerSocketConnection. I have confused with this line , is it is possible to cast base class object to the derived class object?
    Plese help me in this regards
    Thanks in advance
    Sulfikkar

    There is nothing to be confused about. The Connector factory creates an implementation of one of the extentions of the Connection interface and returns it.
    For a serversocket "socket://<port>" it will return an implementation of the ServerSocketConnection interface. You don't need to know what the implementation looks like. You'll only need to cast the Connection to a ServerSocketConnection .

  • Socket programming usin nio package

    hello frens i m new to socket programming
    i come to know that nio packaage provides more sophisticated and efficient API to deal with socket programming issue
    I need to know where i can get tutorial about socket programming using nio pacakage

    Try google
    http://www.google.co.uk/search?q=java+nio+tutorial

  • [Urgent]3G Socket programming

    May I use socket for 3G networks?
    I use the demo provided by the WTK2.5-Beta(NetworkDemo), it works well in the simulator. However, when I download the program to the mobile phone, it seems that the mobile phone that runs ServerSocket cannot create the socket ... all the 2 handsets use a 3G SIM card provided by a Hong Kong ISP smartTone ... What can I do?
    Please help~ provide any web page of codes, thanks very much!

    1.     We want to create a socket connection which can
    remain open and live for ever till it is closed. Is
    this possible in java socket programming?Yes, but it isn't practical in the real networking world. So your code had better be prepared to deal with network failures.
    2.     I am just wondering in order to communicate with
    the third party over the socket connection, does this
    other party requires to run something specific on
    their end? I am not able to understand how will my
    java code communicate with their server otherwise.It has nothing to do with java. Sockets send and recieve messages. The applications at either end, regardless of the language that they are written in, must handle those messages.
    3.     Can we send and receive data over the socket
    created and also is their specific format for the
    data? Yes.
    Can we send files of data over this connection?Yes. (Although I don't know why you would need to do that if you are doing credit card auths.)
    It would be great if someone can comment on these
    questions and also if possible please provide some
    code that can create socket connection.The tutorial.....
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • Can i run UDP  client and UDP  server socket program in the same pc ?

    hi all.
    when i execute my UDP client socket program and UDP server socket program in the same pc ,
    It's will shown the error msg :
    "Address already in use: Cannot bind"
    but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
    anybody know what's going on ?
    any help will be appreciated !

    bobby92 wrote:
    i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
    The server should be using that constructor, the client should not be specifying a port.
    so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to.

  • RESTFUL Web Services vs Socket Programming Performance

    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?
    Tnx.
    Ayberk

    ayberkcansever wrote:
    Hi guys,
    I will have an application which will have a service serving about to 30 million users/day and a mean of 5 requests/user.
    It means that there will be about 150 million requests per day. I will have two servers behind a load balancer and my clients will be both Java and C++.
    I think to implement RESTFUL Web Services but afraid of performance issues.
    Did you have a knowledge about the performances of web service and socket programming in such a high loaded project?It depends on the CPUs, RAM, disks, and network configurations of those servers.
    It depends on how the requests are distributed throughout the day.
    It depends on how big the requests are and how big the responses are.

  • HELP : Convert socket programming from Ipv4 to IPv6

    Hi all,
    I need help in converting my Ipv4 socket programing to Ipv6. How can I do this? I already have an Ipv4 socket programming that is working but when I tried to convert it to Ipv6 it doesn't work .
    this is my Ipv4 socket programming :
    DatagramPacket sendPacket;
    DatagramSocket sock;
    ip = jtfDIP.getText().trim();
    try{
    sock = new DatagramSocket();
    add = InetAddress.getByName(ip);
    sendPacket = new DatagramPacket(buf,buf.length,add,port);
    Please help me. How can I convert this to Ipv6. Thank you.

    Socket sock = new Socket("host");
    or
    Socket sock = new Socket("192.168.1.1");
    or
    Socket sock = new Socket("www.host.com");
    or
    Socket sock = new Socket("hhhh.hhhh.hhhh.hhhh");
    Get it? Just use whatever host, domain name, or IP you need, the underlying native code does the work - you'll never need to do anything, for the most part.

  • How to control tcp connection with java tcp socket programing ??

    Hi,
    I am connecting a server as using java socket programming.
    When server close the connection (socket object) as using close() method ,
    I can not detect this and My program continue sending data as if there is a connection with server.
    How to catch the closing connection ( socket ) with java socket programming.
    My Client program is as following :
    import java.io.PrintWriter;
    import java.net.Socket;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        try
                          socket = new Socket("localhost",5555);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            pw.println(i+". message is being send.");
                            Thread.sleep(5000);
        } catch (Exception ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

    I changed the code as following. But I couldn't catch the EOFException when I read from the socket. How can I catch this exception ?
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class client
      public client()
       * @param args
      public static void main(String[] args)
        Socket socket=null;
        PrintWriter pw=null;
        BufferedReader bufIn=null;
        InputStreamReader inRead=null;
        InputStream in=null;
        try
                          socket = new Socket("localhost",5555);
                          in = socket.getInputStream();
                          inRead = new InputStreamReader(in);
                          bufIn = new BufferedReader(inRead);
                          pw = new PrintWriter(socket.getOutputStream(),true);
                          int i=0;
                          while (true)
                            i++;
                            try
                              bufIn.readLine();
                              pw.println(i+". message is being send.");
                              System.out.println(i+". message has been send");
                            } catch (Exception ex2)
                              System.out.println(ex2.toString());
                              System.out.println(i+". message could not be send");
                            } finally
                            Thread.sleep(5000);
        } catch (EOFException ex)
                          ex.printStackTrace();
        } catch (InterruptedException ex)
                          ex.printStackTrace();
        } catch (IOException ex)
                          ex.printStackTrace();
        } finally
                          try
                            if(pw!=null)pw.close();
                            if(socket!=null)socket.close();
                          } catch (Exception ex)
                            ex.printStackTrace();
                          } finally
    }

  • About Socket program in ABAP

    Hi all,
    Can I do Socket program in ABAP?
    I know nothing about that,Can anyone help?
    Thanks very much.
    Pole

    Within ABAP you have access to OLE objects - take a look at ABAB stement SET PROPERTY.
    In our production we have some scale weights connected to a PC. On the PC an external vendor has created an OLE obejct that can retur te current state and weight of the scale weight directly into a SAP screen.
    I guess if you can write an OLE obejct that can handle it - it is possible.

  • First Very Simple Socket Program

    Hello,
    I am learning about Sockets and ServerSockets and how I can use the. I am trying to make the simplest server/client program possible just for my understanding before I go deper into it. I have written two programs. theserver.java and theclient.java the sere code looks like this....
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class theserver
      public static void main(String[] args)
      {   //  IOReader r = new IOReader();
            int prt = 3333;
            BufferedReader in;
             PrintWriter out;
            ServerSocket serverSocket;
            Socket clientSocket = null;
    try{
    serverSocket = new ServerSocket(prt);  // creates the socket looking on prt (3333)
    System.out.println("The Server is now running...");
    while(true)
        clientSocket = serverSocket.accept(); // accepts the connenction
        clientSocket.getKeepAlive(); // keeps the connection alive
        out = new PrintWriter(clientSocket.getOutputStream(),true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         if(in.ready())
         System.out.println(in.readLine()); // print it
    catch (IOException e) {
        System.out.println("Accept failed:"+prt);
    }and the client looks like this
    import java.net.*;
    import java.io.*;
    public class theclient
    public static void main(String[] args)
        BufferedReader in;
        PrintWriter out;
        IOReader r = new IOReader();
        PrintWriter sender;
        Socket sock;
      try{
        sock = new Socket("linuxcomp",3333);  // creates a new connection with the server.
        sock.setKeepAlive(true); // keeps the connection alive
        System.out.println("Socket is connected"); // confirms socket is connected.
        System.out.println("Please enter a String");
         String bob = r.readS();
          out = new PrintWriter(sock.getOutputStream(),true);
        out.print(bob); // write bob to the server
      catch(IOException e)
           System.out.println("The socket is now disconnected..");
    }If you notice in the code I use a class I made called IOReader. All that class is, is a buffered reader for my System.in. (just makes it easier for me)
    Ok now for my question:
    When I run this program I run the server first then the client. I type "hello" into my system.in but on my server side, it prints "null" I can't figure out what I am doing wrong, if I am not converting correctly, or if the message is not ever being sent. I tried putting a while(in.read()) { System.out.println("whatever") } it never reaches a point where in.ready() == true. Kinda of agrivating. Because I am very new to sockets, I wanna aks if there is somthing wrong with my code, or if I am going about this process completely wrong. Thank you to how ever helps me,
    Cobbweb

    An example of Creating a Client Socket (Java socket programming tutorial)
    try {
            InetAddress addr = InetAddress.getByName("hotdir.biz");
            int port = 80;
            // This constructor will block until the connection succeeds
            Socket socket = new Socket(addr, port);
        } catch (UnknownHostException e) {
        } catch (IOException e) {
        // Create a socket with a timeout
        try {
            InetAddress addr = InetAddress.getByName("hotdir.biz");
            int port = 80;
            SocketAddress sockaddr = new InetSocketAddress(addr, port);
            // Create an unbound socket
            Socket sock = new Socket();
            // This method will block no more than timeoutMs.
            // If the timeout occurs, SocketTimeoutException is thrown.
            int timeoutMs = 2000;   // 2 seconds
            sock.connect(sockaddr, timeoutMs);
        } catch (UnknownHostException e) {
        } catch (SocketTimeoutException e) {
        } catch (IOException e) {
        }See socket tutorial here http://www.developerzone.biz/index.php?option=com_content&task=view&id=94&Itemid=36

Maybe you are looking for