473,614 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a client also be a server, socket/serversocket

153 New Member
Hi,

i have created my own messaging program which entails basically having a application with a serversocket listening for connections and then does it's thing when it receives a connectin from the client socket.

My question is how would i have both listening rather than having to have a client/server scenario so that either can be woken (server) and either can start conversation (client).

Regards

Brendan
Oct 30 '08 #1
8 1860
myusernotyours
188 New Member
Hi,

Just have a thread that listens and another that makes a connection. i.e have a ServerSocket in one thread and a Socket in the other.

If you don't know how to do threading, you can google for java concurrency. The Threading API is pretty easy to use.

Regards,

Alex.
Oct 31 '08 #2
brendanmcdonagh
153 New Member
cheers for that. funnily enough i am just about to read abouthreads.

So i have an app that is capable of being a server an creating a socket when .accept() or making a connection if user chooses it to be a client, and this is done by user starting a thread by there choice.

So a conditional statement is needed if(server.accep t())
{
do this
}


although i know that method doesn't return a boolean but a socket, so can any one offer me a direction on this matter please?

Regards

brendan
Oct 31 '08 #3
JosAH
11,448 Recognized Expert MVP
cheers for that. funnily enough i am just about to read abouthreads.

So i have an app that is capable of being a server an creating a socket when .accept() or making a connection if user chooses it to be a client, and this is done by user starting a thread by there choice.

So a conditional statement is needed if(server.accep t())
{
do this
}


although i know that method doesn't return a boolean but a socket, so can any one offer me a direction on this matter please?
That's just programming; if you'd read the API documentation for ServerSocket
you'd know that the accept() method only returns when a client has successfully
connected to the server, so:

Expand|Select|Wrap|Line Numbers
  1. Socket client= serverSocket.accept();
  2. serve(client);
  3.  
There is no condition; simply serve the client (in another thread).

kind regards,

Jos
Oct 31 '08 #4
brendanmcdonagh
153 New Member
thanks for your help jos, im confused though mate and i have read serversocket and socket api on numerous occasions this week, first by what you mean by serve(client) and also by the following , it's ok waiting for a connection and getting it to do an action when .accept() is executed but what if the class that is currently a serversocket(li stener) wanted to initiate a connection, so in other words it also has the ability to initiate a connection rather than just do something when a connection is initiated with it. So the only way i can understand it at the moment is integrating the client code i have with the server code on both computers i have.

I really hope you understand what im trying to do and can offer me a way to understand how to do it, how can i say it... It's not a code issue it's a design issue if that makes sense.

regards

Brendan
Oct 31 '08 #5
JosAH
11,448 Recognized Expert MVP
I really hope you understand what im trying to do and can offer me a way to understand how to do it, how can i say it... It's not a code issue it's a design issue if that makes sense.
Suppose you and I have to talk to each other; we each take turns so one of us
has to start talking. It's just an agreement, we can't just both wait until the other
one starts talking and we can't just start talking. We have to follow a certain protocol.
The party who starts the talking is the client, the other one is the server. The client
has to make him/itself known to the server. It's all just an agreement. Of course
a server can also be a client w.r.t. other servers and vice versa.

kind regards,

Jos
Oct 31 '08 #6
brendanmcdonagh
153 New Member
Jos, you have helped on many occasions and i appreciate your help and with you reading my posts i hope you know i have never wanted someone just to do it for me but w.r.t your last thread,

please tell me how?

I'll post my client code because by the sounds of the messages it's a case of a couple of lines of code

Expand|Select|Wrap|Line Numbers
  1. /* 
  2.  * Main.java 
  3.  * 
  4.  * Created on 28 October 2008, 13:19 
  5.  * 
  6.  * To change this template, choose Tools | Options and locate the template under 
  7.  * the Source Creation and Management node. Right-click the template and choose 
  8.  * Open. You can then make changes to the template in the Source Editor. 
  9.  */ 
  10.  
  11. package clientside; 
  12.  
  13. import java.io.*; 
  14. import java.net.*; 
  15. import java.util.*; 
  16. import javax.swing.*; 
  17. import java.awt.*; 
  18. import java.awt.event.*; 
  19.  
  20.  
  21. public class Main implements ActionListener 
  22.     public static JFrame aFrame; 
  23.     public static JButton aButton; 
  24.     public static JButton aButton2; 
  25.     public static JTextField inputArea; 
  26.     public static JTextArea output; 
  27.  
  28.     static ServerSocket server; 
  29.     static Socket socket; 
  30.     static PrintStream outStream; 
  31.     static BufferedReader inStream; 
  32.     static String aName;
  33.     static String address;
  34.     static int port;
  35.  
  36.  
  37.  
  38.     public Main() 
  39.     { 
  40. aFrame = new JFrame(); 
  41. aFrame.setSize(500, 500); 
  42. aFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  43. aFrame.setTitle("Input your message"); 
  44. aFrame.setLayout(new BorderLayout()); 
  45.  
  46. aFrame.setVisible(true); 
  47.  
  48. aButton = new JButton(); 
  49. aButton.setText("Press to send message"); 
  50. aButton.setSize(200, 25); 
  51. aButton.addActionListener(this); 
  52. aFrame.add(aButton, BorderLayout.NORTH); 
  53.  
  54.  
  55.  
  56.  inputArea = new JTextField(50); 
  57. inputArea.setVisible(true); 
  58. inputArea.addActionListener(this);
  59. aFrame.add(inputArea, BorderLayout.SOUTH); 
  60.  
  61. output = new JTextArea(25, 50); 
  62. output.setVisible(true); 
  63. aFrame.add(output, BorderLayout.CENTER);
  64.  
  65.  
  66.  
  67.     } 
  68. public static void main(String[] args) 
  69. try 
  70. {     
  71.     Main aMain = new Main();
  72.  
  73.     aName = JOptionPane.showInputDialog(null, "Enter Your Name : ",
  74. "Input Box", 1);
  75.     address = JOptionPane.showInputDialog(null, "Enter IP or address : ",
  76. "Input Box", 1);
  77.     String aPort = JOptionPane.showInputDialog(null, "Enter port to connect through : ",
  78. "Input Box", 1);
  79.     port = Integer.parseInt(aPort);
  80.  
  81.  
  82.      socket = new Socket(address, port); 
  83.     inStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
  84.     outStream = new PrintStream(socket.getOutputStream()); 
  85.  
  86.  
  87.  
  88.     String line;
  89.  
  90.       while  (!(line = inStream.readLine()).equals("exit") )
  91.       {
  92.         Main.output.append (line + '\n');
  93.  
  94.       }
  95.  
  96.      socket.close();
  97. catch (Exception anException) 
  98.     System.out.println("Error: " + anException); 
  99. public void actionPerformed(ActionEvent e) 
  100.     String aString = Main.inputArea.getText();
  101.     if((e.getSource() == aButton) || (e.getSource() == inputArea))
  102.     {
  103.  
  104.     if((aString.equals("exit")) || (aString.equals(" exit")))
  105.         { 
  106.  
  107.  
  108.             try
  109.             {
  110.  
  111.                 System.exit(1);
  112.                 socket.close();
  113.             }
  114.             catch(Exception anException)
  115.             {
  116.  
  117.             }
  118.         } 
  119.     else 
  120.     { 
  121.         Main.output.append (aName + " says " + aString + '\n');
  122.         Main.inputArea.setText(" ");
  123.         Main.outStream.println(aName + " says " + aString); 
  124.  
  125.  
  126.     } 
  127. }
  128. }
  129.  
  130.  
  131. }
  132.  
How can i make this listen and do something when a connection is made to it or if a user decides to, connect to a server and do something (what it currently does)?

Regards

Brendan
Oct 31 '08 #7
JosAH
11,448 Recognized Expert MVP
How can i make this listen and do something when a connection is made to it or if a user decides to, connect to a server and do something (what it currently does)?
Simply use another thread again that manages the accept()s.

kind regards,

Jos
Nov 1 '08 #8
brendanmcdonagh
153 New Member
ok, will do. thank you jos

Brendan
Nov 1 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1695
by: Adrian Hjelmslund | last post by:
Hi group, I'm doing an internetclient via cellphone/gprs that sends a request to html sites. The client I've made work great on all sites......except the only site where I need it :-/ I guess that the problem is that my website host have a firewall, or maybe just some serversettings, that inhibits my client from getting the site I request.
2
11289
by: Rajesh | last post by:
Hi, We have a socket server app in Java and the client application in C++. When we try to connect 60 clients simultaneously from C++ using threads, only 55-56 connections are successfull, rest are not connected(Connection refused error). For one connection everything works fine. In server side each connection is handled in seperate thread.
12
5625
by: Eugene A | last post by:
Hello. I am trying to compile a linux socket server and a client in cygwin on windows. The g++ version is 3.3.1. The source was obtained from this location: http://www.linuxgazette.com/issue74/tougher.html ServerSoccket.cpp apparently compiles OK. Socket.cpp has a problem. Here's
0
2771
by: netgeni59 | last post by:
Hello fellow C# friends, I am trying to write a C# TCP client that was formerly written in Java. The server must still remain in Java. I cannot get text data from the C# client to be received by the Java TCP server. No matter how I try to send data from the client to the server, the Java server DataInputStream readUTF() method never returns with any data. Can someone please shed some light on this problem? Thanks.
4
8196
by: yaron | last post by:
Hi, I have a problem when sending data over TCP socket from c# client to java server. the connection established ok, but i can't send data from c# client to java server. it's work ok with TcpClient, NetworkStream and StreamWriter classes. but with low level socket it doesn't work (When using the Socket class Send method).
2
10101
by: giangiammy | last post by:
hi all, I'd like to implement a server socket in java: something linke the following example. The problem is that the HTML has not the permission to execute instruction serverSocket = Components.classes. createInstance(Components.interfaces.nsIServerSocket);
4
3250
by: SpreadTooThin | last post by:
client: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.1.101", 8080)) print 'Connected' s.send('ABCD') buffer = s.recv(4) print buffer s.send('exit')
4
6506
by: rajbala | last post by:
Hi all, I am a newbie to JSP. I had a program in client and server by using java. But i want the same program in JSP. Please help me. server: // TCP server which waits for messages from a client - non threaded import java.io.*;
1
21406
by: diegoblin | last post by:
Hi, i kind of new to java and i want to transfer a file between a server and a client. I know i have to use InputStream and OutputStream, but i don't know how to do it properly. So far i think i've managed to do the client part. i read the content of a file, "hi.txt", and i send it to the server. The problem is in the server part, i do not know how to write the file in the server. Thanks in advance for your help Here is my code for the...
10
4229
by: Elaine121 | last post by:
Hi i've been batteling for hours and can't seem to find the problem. When my server runs and I press the connect button the gui freezes until the client gui is terminated.. only then the gui becomes active again and displays the messages. Here is my server code: import java.io.*; import java.net.*; public class serverForm extends javax.swing.JFrame { private PrintWriter output = null;
0
8142
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8640
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8589
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7114
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6093
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5548
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4136
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1438
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.