Server/Client Socket Connection
Hi, I am trying to program a simple server/client socket connection program, the main function is to send and receive objects between them. I somehow went wrong and the connection between them keeps terminating right after establishing connection. Is there anything I can do to resolve this?
This is gonnna be kinda long post.. sorry. These are the code that starts and ends the socket connection. I'm kinda desperate for this to work.. so thanks in advance.
appinterface.java:
//Set up server to receive communications; process connections. 1x.
public void runServer () {
try {
//Create a ServerSocket
server = new ServerSocket(12345, 100);
try {
waitForSockConnection(); //Wait for a connection.
getSockStreams(); //Get input & output streams.
establishDbConnection(); //Open up connection to DB.
finally {
closeSockConnection(); //Close connection.
//Process problems with I/O
catch(IOException ioException) {
displayMessage("I/O Error: " + ioException);
runServer();
//Wait for connection to arrive, then display connection info
private void waitForSockConnection() throws IOException {
displayMessage("Waiting for connection");
connection = server.accept(); //Allow server to accept connection.
displayMessage("Connection received from: " + connection.getInetAddress().getHostName());
//Get streams to send and receive data.
private void getSockStreams() throws IOException {
//Set up output streams for objects
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
output.flush(); //Flush output buffer to send header information.
//Set up input stream for objects.
ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
try {
classHolderServer holderObj = new classHolderServer();
holderObj = (classHolderServer)input.readObject();
processSockConnection(holderObj);
displayMessage("Got I/O Streams");
//Catch problems reading from client
catch (ClassNotFoundException classNotFoundException) {
displayMessage("Unknown object type received");
//Process connection with client.
private void processSockConnection(classHolderServer holderObj) throws IOException {
//sendMessage("Connection Successful");
//True is query, and false is auth.
if(holderObj.type1==true)
processDbStatement(holderObj.type2, holderObj.sqlquery);
else {
authCheck(holderObj.userName, holderObj.passWord);
if(!authCheck)
closeDbConnection();
//Send messages to client.
private void sendMessage(String message) {
// Send message to client
try {
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
output.writeObject(message);
output.flush();
displayMessage("Message Sent:" + message);
catch (IOException ioException) {
displayMessage("\nError Sending Message: " + message);
//Send object to client
private void sendObject(Object holderObj) {
// Send object to client
try {
ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
output.writeObject(holderObj);
output.flush();
displayMessage("\nObject sent");
//Process problems sending object
catch (IOException ioException) {
displayMessage("\nError writing object");
//Close streams and socket.
private void closeSockConnection() {
displayMessage("Terminating connection");
try {
//output.close();
//input.close();
connection.close();
closeDbConnection();
this.userName = null;
this.passWord = null;
this.receiverId = 0;
this.authCheck = false;
catch (IOException ioException) {
displayMessage("I/O Error: " + ioException);
}Client:
private void runClient() {
//Connect to sever and process messages from server.
try{
connectToServer();
getStreams();
processConnection();
//Server closed connection.
catch(EOFException eofException) {
//displayMessage"Client Terminated Connection");
//Process problems communicating with server.
catch (IOException ioException) {
//displayMessage"Communication Problem");
finally {
closeConnection();
//Connect to server
private void connectToServer() throws IOException {
//displayMessage("Attempting connection\n");
//Create Socket to make connection to sever.
client = new Socket(InetAddress.getByName(chatServer), 12345);
//Display connection information
//displayMessage("Connected to: " + client.getInetAddress().getHostName());
//Get streams to send and receive data.
private void getStreams() throws IOException {
//Set up output stream for objects.
ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
output.flush(); //Flush outout buffer to send header information.
//Set up input stream for objects.
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
//displayMessage("\nGot I/O streams\n");
//Close socket connection.
private void closeConnection() {
//displayMessage("\nClosing connection");
try {
ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
output.close();
ObjectInputStream input = new ObjectInputStream(client.getInputStream());
input.close();
client.close();
authCheck=false;
catch(IOException ioException) {
ioException.printStackTrace();
//Send data to server.
private void sendObject(classHolderClient queryObj) {
try {
output.writeObject(queryObj);
output.flush();
//displayMessage("Please wait..");
//Process problems sending object.
catch (IOException ioException) {
//displayMessage("\nError writing object");
//Process connection with server.
private void processConnection() throws IOException {
try{
classHolderClient holderObj = new classHolderClient();
holderObj = (classHolderClient)input.readObject();
if(holderObj.type2==2) {
this.authCheck=holderObj.authCheck;
this.userName=holderObj.userName;
this.passWord=holderObj.passWord;
catch(ClassNotFoundException classNotFoundException) {
//displayMessage(classNotFoundException);
}
private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());Like this? But this will cause an error asking me to catch an exception:
C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
^
C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
^
2 errors
Similar Messages
-
Java Chat (Server, Client Socket Connection)
Assignment:
The assignment is to deliver two source codes that can run a Server (1) and Clients (2) in order to create a simpel chat program. The server has to wait and check an IP (localhost) + Port, and the client has to connect to that port and create a socket connection. The only thing that should be done is create a new socket connection for each client... and when a client sends a message, the message should be delivered to all clients connected to the server.
Problem...
However I can read an edit Java, it's difficult for me to write it. I allready found many turturials about socket connections on the internet, and tried to edit those, but they don't really do what I want unless I really write new shit. Is there a way you guys can help me with this, or that you find a really good website that fits my question?According to me ,
take string variable 'str'
Take some class ,I think u already taken.....
Scoket scoket = new Socket(IP,port);
OutputStream out;
IInputStream in;
in = socket.getInputStream();
out = socket.getOutputStream();
If sends the msg then use
out.writeObject(str);
This line sends data to the other user
msg resivce from client then use
str = in.readInput();
& this str set to the any objects out put .
Such as TextField.setText(str);
//Server.class
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Server extends JFrame
private JTextField enterdField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter=1;
public Server()
super("Server");
enterdField = new JTextField();
enterdField.setEditable(false);
enterdField.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent event)
sendData(event.getActionCommand());
//System.out.println(event.getActionCommand());
enterdField.setText("");
add(enterdField,BorderLayout.NORTH);
displayArea = new JTextArea();
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
public void runServer()
try
server = new ServerSocket(12345,100);
while(true)
try
waitForConnection();
getStreams();
processConnection();
catch(EOFException eofexception)
displayMessage("\nServer terminated connection");
finally
closeConnection();
counter++;
catch(IOException ioException)
ioException.printStackTrace();
private void waitForConnection() throws IOException
displayMessage("Waiting for connection");
connection = server.accept();
//System.out.println(server.accept());
System.out.println(connection.getInetAddress());//Server Address and Hostname.
displayMessage("Connection"+counter +"received from :"+connection.getInetAddress().getHostName());
private void getStreams() throws IOException
System.out.println("Start getStream");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
displayMessage("\nGot I/O stream\n");
private void processConnection() throws IOException //Read data from Client for Server.
String message="Connection sucessful To Client";
sendData(message);
int i=0;
setTextFieldEditable(true);
do
try
message =(String) input.readObject();//For Client
System.out.println("Input from :"+message);//From Client
displayMessage("\n" + message);
System.out.println("\n" + i++);
catch(ClassNotFoundException classnotfoundexception)
displayMessage("\nUnknown object type recived");
while(!message.equals("CLIENT>>>TERMINATE"));
private void closeConnection()
displayMessage("\nTeminating connection");
setTextFieldEditable(false);
try
output.close();
input.close();
connection.close();
catch(IOException ioException)
ioException.printStackTrace();
private void sendData(String message)//Write data to the Client from the Server.
try
output.writeObject("SERVER>>>"+message);//For Client side.
System.out.println(message);
output.flush();
displayMessage("\nSERVER>>>"+message);//On server side.
catch(IOException ioException)
displayMessage("\nError writing object");
private void displayMessage(final String messageToDisplay)
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append(messageToDisplay);
private void setTextFieldEditable(final boolean editable)
SwingUtilities.invokeLater(
new Runnable()
public void run()
enterdField.setEditable(editable);
public static void main(String q[])
Server app = new Server();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.runServer();
//Client.class
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Client extends JFrame
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message="";
private String chatServer;
private Socket client;
public Client (String host)
super("Client");
chatServer=host;
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(
new ActionListener()
public void actionPerformed(ActionEvent event)
sendData(event.getActionCommand());
enterField.setText("");
add(enterField,BorderLayout.NORTH);
displayArea = new JTextArea();
add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
public void runclient()
try
connectToServer();
getStreams();
processConnection();
catch(EOFException eofException)
displayMessage("\nClient treminated connection");
catch(IOException ioException)
ioException.printStackTrace();
finally
closeConnection();
private void connectToServer() throws IOException
displayMessage("Attempting connection\n");
client = new Socket(InetAddress.getByName(chatServer),12345);
displayMessage("Connect to:"+client.getInetAddress().getHostName());
private void getStreams() throws IOException
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());
//Thread t = new Thread(this,"Thread");
//t.start();
displayMessage("\nGot I/O stream\n");
private void processConnection( ) throws IOException
setTextFieldEditable(true);
do
try
message=(String)input.readObject();
displayMessage("\n"+message);
catch(ClassNotFoundException classnotfoundexception)
displayMessage("\nUnknown object type received");
while(!message.equals("SERVER>>>TERMINATE"));
private void closeConnection()
displayMessage("\n Closing connection");
setTextFieldEditable(false);
try
output.close();
input.close();
client.close();
catch(IOException ioException)
ioException.printStackTrace();
private void sendData(String message)
try
output.writeObject("CLIENT>>>"+message);
//System.out.println(message);
output.flush();
displayMessage("\nCLIENT>>>"+message);
catch(IOException ioException)
displayArea.append("\n Error writing object");
private void displayMessage(final String MessageToDisplay)
SwingUtilities.invokeLater(
new Runnable()
public void run()
displayArea.append(MessageToDisplay);
private void setTextFieldEditable(final boolean editable)
SwingUtilities.invokeLater(
new Runnable()
public void run()
enterField.setEditable(editable);
public static void main(String q[])
Client app;
if(q.length==0)
app = new Client("127.0.0.1");
else
app = new Client(q[0]);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.runclient();
Use this example .....
Give me reply.My method is correct or not
All the best -
Simple server/client socket in applets code.
Can anyone please help me with Java sockets ? I want to create an applet that simply checks if it's still online. This means that i'll be using this applet thru modem(that is, dial-up connection). All i want the applet to do is send a signal to the server and the server answer back that it is still online. The server should be able to handle multiple sends and receives. I need just a simple code for me to work on (both server and client). The client doesn't have to send any special message to the server and vice versa.
Thanks.Below is the code for both Applet and Servlet .I think this will solve your problem.
Applet:
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
public class OnlineApplet extends Applet implements Runnable
private static Thread thread;
private static HttpURLConnection URLConn;
public void init()
try
//Connect to the URL where servlet is running.
URL url = new URL("http://localhost/servlet/OnlineServlet");
URLConn = (HttpURLConnection)url.openConnection();
URLConn.setDoInput(false);
URLConn.setDoOutput(true);
catch (Exception ex)
thread = new Thread(this);
public void start()
thread.start();
public void paint(Graphics g) {}
public void stop() { }
public void destroy() { }
public void run()
while(true)
try
thread.sleep(1000 * 60);
sendConfirmation();
catch (Exception ex)
private void sendConfirmation() throws Exception
DataOutputStream dos = new DataOutputStream(URLConn.getOutputStream());
dos.writeChars("Fine");
dos.flush();
dos.close();
Servlet:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class OnlineServlet extends HttpServlet implements Runnable
public static Hashtable hsh;
private static Thread thread;
public void init(ServletConfig scon) throws ServletException
hsh = new Hashtable();
thread = new Thread(this);
public void service(HttpServletRequest req, HttpServletResponse res)
String strHostName = req.getRemoteHost();
if(hsh.containsKey(strHostName))
updateHash(strHostName);
else
hsh.put(strHostName, System.currentTimeMillis() + "");
private void updateHash(String strHostName)
hsh.remove(strHostName);
hsh.put(strHostName, System.currentTimeMillis() + "");
public void run()
while(true)
try
thread.sleep(1000 * 120);
catch (Exception ex)
validateUsers(System.currentTimeMillis());
private void validateUsers(long msec)
Enumeration keys = hsh.keys();
int size = hsh.size();
while(keys.hasMoreElements())
String strKey = keys.nextElement().toString();
String strLong = hsh.get(strKey).toString();
long lg1 = Long.parseLong(strLong);
if((lg1 - msec) > 100000)
// This means there is no response from user . That means he is not online. So you can remove from hashtable.
hsh.remove(strKey); -
Can Java make server side socket connections?
I plan on placing a java file (application or applet I don't know) on a website and have my application connect to the java file and tell it to connect to another host (outside of the website's domain) and send and receive data. Is this possible? If not why? If so, then should it be an applet or an application? Would I need to have it listen on a specific port or what?
I read this (http://java.sun.com/sfaq/):
"How can an applet open a network connection to a computer on the internet?
Applets are not allowed to open network connections to any computer, except for the host that provided the .class files. This is either the host where the html page came from, or the host specified in the codebase parameter in the applet tag, with codebase taking precendence.
For example, if you try to do this from an applet that did not originate from the machine foo.com, it will fail with a security exception:
Socket s = new Socket("foo.com", 80, true);"
- sun
And it through me for a loop.Think about this:
Any webpage may contain an applet.
Imagine the security implications if an applet could do whatever the developer wanted (erase your hard-drive, read your data, run your programs) without your permission.
Network connections are another example of the same thing.
Imagine you visit a webpage and an applet pops up that uses your computer to make a connection to government websites in an attempt to hack them.
Yikes.
So basically what happens (by default) is an applet starts of with a reduced set of permissions to protect the end user.
An application (by default) starts with more permissions you'd expect an application to have.
This is all configurable by the person who will be running the Applet or application. If someone trusts you, they can set up their runtime to give your applet all permissions, or give it a particular set of permissions. Or you can sign the applet with a digital signature, and if the end user trusts the certificate, and trusts you they can give your applet permissions that way.
Java Security, however, is not something that can be covered in one post on the forums.
You should probably look for some online tutorials/documentation or get a good book. -
How to detect client socket shutdowns in server socket
Hi,
Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
if (serverSocket == null){
serverSocket = new ServerSocket(4511);
clientSocket = serverSocket.accept();
System.out.println("Accepted client request ... ");
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Input / Output streams intialized ...");
while (true){
System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
//get Message from Queue Head (also removes it)
message = getQueueMessage(messageQueue);
//format and send to Third Party System
if (message != null){
out.println(formatMessage(message));
System.out.println("Sent to Client... ");
//sleep
System.out.println("Going to sleep 5 sec");
Thread.sleep(5000);
System.out.println("Wake up ...");
}catch(IOException ioe){
System.out.println("initSocketServer::IOException : " + ioe.getMessage());
}catch(Exception e){
System.out.println("initSocketServer::Exception : " + e.getMessage());
}I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
Is Client Socket Closed : false
Is Client Socket Connected : true
Is Client Socket Bound : true
Is Client Socket Input Shutdown : false
Is Client Socket Output Shutdown : false
Is Server Socket Bound : true
Is Server Socket Closed : false
So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
Appreciate much, thanks.Crossposted and answered.
-
How to Create a Single Backend Socket connectivity in a Server Socket Pgm
Hi Everybody,
I have a written a Server Socket which connects to back end socket and receiving the data and sending back to the front end. But as per my client requirement i need to create only one socket at the back end. But the code I have written is creating new sockets for each request. Is there any way to use the single client socket connection for all the transactions. I have attached the sample code for the reference.
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class serl implements Runnable
ServerSocket serversocket;
Socket clientsoc;
Socket fromclient;
PrintStream streamtoclient;
BufferedReader streamfromclient;
SocketChannel socket_channel=null;
Thread thread;
public serl()
try
serversocket = new ServerSocket(1001);//create socket
clientsoc = new Socket("10.100.53.145",200);
socket_channel = clientsoc.getChannel();
catch(Exception e)
System.out.println("Socket could not be created "+e);
thread=new Thread(this);
thread.start();
public void run()
try
while(true)
PrintStream streamtobackend=null;
BufferedReader streamfrombackend = null;
fromclient=serversocket.accept();//accept connection fromclient
streamfromclient=new BufferedReader(new InputStreamReader((fromclient.getInputStream())));
//create a input stream for the socket
streamtoclient=new PrintStream(fromclient.getOutputStream());
//create an a output stream for the socket
String str=streamfromclient.readLine();
//read the message sent by client
System.out.println("Output Input From Vtcpd "+str);
streamtobackend.print(str);
streamtobackend = new PrintStream(clientsoc.getOutputStream());
//create an a output stream for the backend socket
streamfrombackend = new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
//create a input stream for the backend socket
str=streamfrombackend.readLine();
System.out.println("Output From Backend Client"+str);
streamtoclient.println(str);
}//end of while
catch(Exception e)
System.out.println("Exception "+e);
finally
try
fromclient.close();
catch(Exception e)
System.out.println("could not close connection "+e);
public static void main(String ar[])
new serl();
}Srikandh,
Create a singelton pattern for you socket ( IP, port, etc..) and each time you read the input stream and write to the output stream, do the following to the socket to reset it in the working thread
fromclient.getInputStream().mark(0);
fromclient.getInputStream().reset();Hope this could help
Regards,
Alan Mehio
London,UK -
My first Server/Client Program .... in advise/help
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,
Cobbwebhere's my simple server/client Socket :
Server:
import java.net.*;
import java.io.*;
public class server
public static void main(String a[])
ServerSocket server=null;
Socket socket=null;
DataInputStream input=null;
PrintStream output=null;
try
server=new ServerSocket(2000);
socket=server.accept();
input = new DataInputStream(socket.getInputStream());
output = new PrintStream(socket.getOutputStream());
//output.println("From Server: hello there!");
String msg="";
while((msg=input.readLine()) != null)
System.out.println("From Client: "+msg);
catch(IOException e)
catch(Exception e)
}Client:
import java.net.*;
import java.io.*;
public class client
static private Socket socket;
static private DataInputStream input;
static private PrintStream output;
public static void main(String a[])
try
socket=new Socket("10.243.21.101",2000);
System.out.println("\nconnected to: \""+socket.getInetAddress()+"\"");
input=new DataInputStream(socket.getInputStream());
output=new PrintStream(socket.getOutputStream());
output.println("From Client(Tux): "+a[0]);
String msg="";
//while((msg=input.readLine()) != null)
System.out.println("From Server(Bill): "+msg);
catch(java.io.IOException e)
catch(Exception e)
} -
How to retain socket connection for multiple requests in java 1.3
Hi All,
My problem is to retain client socket connection without opening and closing socket connection for every request.I want to open the socket connection once and send multiple requests one after the other based upon the response over the same socket.Finally I want to close the socket only after completing all my requests and receiving respective responses.I don't want to open and close the socket for each request and response.While at the same time I expect the socket to send each request only after receiving the response for the previous request.
I am using java 1.3 and I am looking for the solution in same version.
Please help me .
Thanx in advance.Look at my response to "Telnet to Unix box from Java"
http://forum.java.sun.com/thread.jsp?forum=31&thread=437231
on "Java Programming" forum. It does exactly that to run the signon and a command. It would be easy to extend it to do multiple commands. -
Multiple socket connection in TC65
Hello!
I connect TC65 with server by socket connection on port 23. I close this socket, output and input streams as well. Because I've read some information from server I want to connect to another device using socket connection on port 43 for example, but it seems it doesn't work. I guess in some way it could be done because I closed previous connection. Any advise?
Lukeok. dear
my another id is [email protected]
Right, I'm getting tired of this already.
NO, I'm not going to send you any code, you lazy nitwit. Neither will anybody here.
Your use of the imperative form in your question is rude. You may talk like that to your colleagues, but in a forum where people answer questions in their spare time and on a voluntary basis this is inacceptable.
You didn't even bother to say "please", at the least. Not that this would have changed much, but at least you wouldn't have been barking.
[url http://www.catb.org/~esr/faqs/smart-questions.html]This document might provide you some orientation.
As for your problem, first find out what exactly it is you want to do. Search the web, as kajbj counselled, it's quite a common task. If you have a specific problem, ask. But, take my advice and never, never ever ask people to "send you code" in a forum. -
Can anybody help me how to connect Flash to a server Using Sockets connection using in AS3.
Use following code UPDATED:
try
var mySocket:Socket = new Socket();
var isConnected:Boolean = false;
var portNumber:Number =8000; //Enter Port number you want to use instead of 8000;
var IPAddress:String = "localhost"; //Enter server IP instead of localhost;
//Valid range of port numbers is 1 to 65535
if (portNumber >= 1 && portNumber <= 65535)
//Create new socket.
mySocket=new Socket ;
//Connect to host and port.
mySocket.connect(IPAddress,portNumber);
//Add listeners to socket to start communicating with the server.
mySocket.addEventListener(IOErrorEvent.IO_ERROR,errorOccured);
mySocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,errorOccured);
mySocket.addEventListener(ProgressEvent.SOCKET_DATA,readFromServer);
mySocket.addEventListener(Event.CONNECT,connectionEstablished);
else
//Show error message
trace("Server is not reachable on port " + portNumber + ".");
ExternalInterface.call("alert","Server is not reachable on port " + portNumber + ".");
catch (e)
//Show error message
trace("Server is not reachable.");
ExternalInterface.call("alert","Server is not reachable.");
function readFromServer(evnt:ProgressEvent):void
//Read message
var str:String = mySocket.readUTFBytes(mySocket.bytesAvailable);
//Remove line breaks.
while (str.indexOf("\n") > -1)
str = str.replace("\n","");
while (str.indexOf("\r") > -1)
str = str.replace("\r","");
//Message from server received...
trace(str);
function writeToServer(toUserName:String, messageStr:String):void
if (isConnected)
var pushStr = "Message from Flash to server";
mySocket.writeUTFBytes(pushStr);
mySocket.flush();
//This function is called when connection to server is successful.
function connectionEstablished(evnt:Event)
//Mark socket connection with the server as connected.
isConnected = true;
function errorOccured(evnt:Event)
//Some error occured
trace("Some error occured!");
ExternalInterface.call("alert","Some error occured!"); -
Multiple clients on socket connection
Hi!
I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
But i would like to refuse connectios, if one client is connected. How can I do that?
In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
Thank you for your help!
concerned Code (if you want to take a look at it):
CLIENT:
socket = new Socket(hostname, echo_port);
SERVER:
try
ServerSocket waitingsocket = new ServerSocket(echo_port);
try
socket= waitingsocket.accept();
System.out.println("Client connected");
ReaderThread reader = new ReaderThread( this, socket );
reader.start();
catch (Exception e)
READER:
public void run()
while (true)
try {
int bytesRead = inStream.read(inputBuffer,
0, inputBuffer.length);
readCallback.tcpUpdate(inputBuffer,bytesRead);
catch (Exception oops)
readCallback.tcpUpdate(null,-1);
Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
- K -
Can't connect to local MySQL server through socket '/var/mysql/mysql.sock'
I'm using the pre-installed versions of php and mysql under Mac OS X Server 10.4.4 running on a G4 and am unable to get anything involving mysql to work.
I ssh to the server and enter various commands in Terminal:
on typing "mysql" I get
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)
and on typing "mysqladmin version" I get
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/var/mysql/mysql.sock' exists!
On typing "sudo mysqld_safe" I get
Starting mysqld daemon with databases from /var/mysql
STOPPING server from pid file /var/mysql/MyServer.local.pid
070722 16:06:05 mysqld ended
/var/mysql/MyServer.local.err contains
070722 16:06:04 mysqld started
070722 16:06:04 [Warning] Setting lowercase_tablenames=2 because file system for /var/mysql/ is case insensitive
070722 16:06:04 InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
070722 16:06:05 InnoDB: Starting log scan based on checkpoint at
InnoDB: log sequence number 0 43634.
/var/mysql has permissions 775.
The line
mysql.default_socket = /var/mysql/mysql.sock
is in /etc/php.ini
whereis mysqladmin ->
/usr/bin/mysqladmin
whereis mysql ->
/usr/bin/mysql
ls /var/mysql ->
MyServer.local.err
ib_logfile1
mysql
ib_logfile0
ibdata1
test
Can't find my.cnf or my.ini anywhere
Can't find mysql.sock anywhere
I'm trying to get a bug database running (mantis) under Mac OS X Server 10.4.4 that I can access from local clients.
I'm trying to follow directions at http://www.mantisbugtracker.com/manual/manual.installation.php
without knowing anything about mysql or php and I'm stuck on step 3:
"Next we will create the necessary database tables and a basic configuration
file."
I get a message saying
"Does administrative user have access to the database? ( Lost connection to MySQL server during query )"
I don't even know if following the mantis directions has resulted in the creation of a database or not. Where would it be?
Thanks for any help.
Intel iMac Mac OS X (10.4.10)I've just done a clean install of OSX Server and added the latest MYSQL packaged installer. Afterwards I found the lock file in /private/tmp/mysql.lock
The easiest way to solve this problem is to create a symbolic link so that the lock file appears to be in right place.
e.g.
cd /var
sudo mkdir mysql <== this assumes the directory is missing
cd mysql
sudo ln -s /private/tmp/mysql.sock mysql.sock
After this msql commands should work fine, and you've not fiddled with the security settings on users/groups.
HTH
Christian -
Unable to connect to the server - windows sockets
//////socket connector method////
bool SocketConnecter::connect(const std::string& ip, size_t port)
size_t uport = htons(port);
std::string sPort = toString(uport);
// Resolve the server address and port
const char* pTemp = ip.c_str();
iResult = getaddrinfo(pTemp, sPort.c_str(), &hints, &result); // was DEFAULT_PORT
if (iResult != 0) {
Verbose::show("\n -- getaddrinfo failed with error: " + toString(iResult), always);
return false;
// Attempt to connect to an address until one succeeds
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
char ipstr[INET6_ADDRSTRLEN];
void *addr;
char *ipver;
// get pointer to address - different fields in IPv4 and IPv6:
if (ptr->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)ptr->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
else { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)ptr->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
// convert the IP to a string and print it:
inet_ntop(ptr->ai_family, addr, ipstr, sizeof ipstr);
printf("\n %s: %s", ipver, ipstr);
// Create a SOCKET for connecting to server
socket_ = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (socket_ == INVALID_SOCKET) {
int error = WSAGetLastError();
Verbose::show("\n -- socket failed with error: " + toString<int>(error), always);
return false;
iResult = ::connect(socket_, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
socket_ = INVALID_SOCKET;
int error = WSAGetLastError();
Verbose::show("WSAGetLastError returned " + toString(error));
continue;
break;
freeaddrinfo(result);
if (socket_ == INVALID_SOCKET) {
int error = WSAGetLastError();
Verbose::show("\n -- unable to connect to server, error = " + toString(error));
return false;
return true;
/////////Test stub////
int main()
title("Testing Socket Client", '=');
try
Verbose v(true);
SocketSystem ss;
SocketConnecter si;
while (!si.connect("localhost", 9080))
Verbose::show("client waiting to connect");
::Sleep(100);
title("Starting string test on client");
clientTestStringHandling(si);
title("Starting buffer test on client");
clientTestBufferHandling(si);
si.sendString("TEST_STOP");
Verbose::show("\n client calling send shutdown\n");
si.shutDownSend();
catch (std::exception& ex)
Verbose::show(" Exception caught:", true);//always = true
Verbose::show(std::string("\n ") + ex.what() + "\n\n");
I am trying to connect to the server, but the connector method shows the message "unable to connect to server"
While debugging i found the iResult to be -1 which makes the socket INVALID_SOCKET
Kindly help resolve thisHi askatral,
connect function can return invalid_socket for many reasons, what does the function WSAGetLastError return?
There are some Variables that I cannot find how it is declared, like "socket_" and "ptr". So I cannot check if there is anything wrong in your code.
Maybe this sample in the document of connect function is helpful for this issue:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx
Best regards,
Shu
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Unable to initialize socket connection to Content Server
Hi,
Webcenter installed on linux, content server installed on windows. Here is the error I see in the log files. I did added the ip address of the linux machine in windows host file but in Spaces I see JCR Connection problem. Any idea on what might be wrong. Here ar the settings I have Repository Connection:
User Name: sysadmin
CIS Socket Type: Socket
Server Host: windowsmachine
Server Port: 5444
Authntication Method: Identity Propagation
javax.jcr.RepositoryException: oracle.stellent.ridc.protocol.ProtocolException: Unable to initialize socket connection to Content Server
at oracle.jcr.impl.ExceptionFactory.repository(ExceptionFactory.java:161)
at oracle.stellent.jcr.IdcPersistenceManagerFactory.createPersistenceManager(IdcPersistenceManagerFactory.java:177)
at oracle.jcr.impl.OracleRepositoryImpl.login(OracleRepositoryImpl.java:444)
at oracle.vcr.jam.LoginTask.call(LoginTask.java:68)
at oracle.vcr.jam.LoginTask.call(LoginTask.java:29)
at oracle.webcenter.concurrent.Submission$2.run(Submission.java:495)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
at oracle.webcenter.concurrent.Submission.runAsPrivileged(Submission.java:509)
at oracle.webcenter.concurrent.Submission.run(Submission.java:436)
at oracle.webcenter.concurrent.Submission$SubmissionFutureTask.run(Submission.java:792)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at oracle.webcenter.concurrent.ModifiedThreadPoolExecutor$Worker.runTask(ModifiedThreadPoolExecutor.java:657)
at oracle.webcenter.concurrent.ModifiedThreadPoolExecutor$Worker.run(ModifiedThreadPoolExecutor.java:682)
at java.lang.Thread.run(Thread.java:619)
Caused by: oracle.stellent.ridc.protocol.ProtocolException: Unable to initialize socket connection to Content Server
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnectionManager.initializeConnection(SocketConnectionManager.java:23)
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnectionManager.initializeConnection(SocketConnectionManager.java:10)
at oracle.stellent.ridc.protocol.impl.SimpleConnectionPool.acquireConnection(SimpleConnectionPool.java:35)
at oracle.stellent.ridc.IdcClient.sendRequest(IdcClient.java:130)
at oracle.stellent.jcr.IdcPersistenceManagerFactory.createPersistenceManager(IdcPersistenceManagerFactory.java:163)
... 15 more
Caused by: oracle.stellent.ridc.protocol.ProtocolException: java.net.ConnectException: Connection refused
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnection.connect(SocketConnection.java:41)
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnectionManager.initializeConnection(SocketConnectionManager.java:21)
... 19 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:180)
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnection.createSocket(SocketConnection.java:111)
at oracle.stellent.ridc.protocol.intradoc.socket.SocketConnection.connect(SocketConnection.java:38)
... 20 moreThis error usually occurs because you have not authorized the client's IP address in UCM. The steps to add the WebCenter host to the list of authorized clients are detailed in section [4.3.1.3.1 of the Installation Guide|http://download.oracle.com/docs/cd/E12839_01/install.1111/e12001/webcenterservice_install.htm#sthref161].
Regards,
Nicolas -
Client not connecting to server. please help
I have been trying to run a sample client-server program, but it doesn't seem to reconise the host name that has been declared in the client program.
i get the following error:
Client Error: java.net.UnknownHostException: Paradoxical
can anyone tell me what the host name should be to allow the client to connect to the server????
bellow the server code:
import java.io.*;
import java.net.*;
* <p>This class doesn't actually deal with the client, it simply
* spawns ClientHandlers that cope with all the i/o.
* @author Stephen Dolphin 01972612
* @see ClientHandler
public class Server {
* Attribute holding the server's listening port number.
private static int portNumber = 80;
* This is this class' only method. It simply waits for requests
* on the given port until it hears something, and then it spawns
* a new handler.
public static void main(String[] args)
// the initial handler number
int socketNumber = 1;
try
ServerSocket server = new ServerSocket(portNumber);
System.out.println("Coffee Pot Server running!");
System.out.println("Waiting for connections on " + portNumber);
// continuous loop
while (true)
// wait for request...
Socket clientSocket = server.accept();
// when received, start new handler!
new ClientHandler(clientSocket, socketNumber).start();
// increment ready for next time.
socketNumber++;
} // while(true)
catch (Exception e)
// catch all errors, and, display string
System.out.println("Server Error: " + e.toString());
} // trycatch
} // main(String[])
} // Server{}The host name to use for the client is the name of the machine that the server is running on. From your error message, the client expects the server to run on 'Paradoxical' but it can't find a machine with that name. You might try to use 'ping Paradoxical' to verify that the machine exists.
If your server is running on the same machine as the client, you can just use 'localhost' as the host name.
Maybe you are looking for
-
Can i use local database in webdynpro
Hai, I want to store a string in the local database. is it possible to store in local dictionary-->structures. using this how cani store , retrieve, update and delete the data in the local dictionary. regards,
-
I MOVIE....Quicktime will not allow me to view it
I am running Yosemite. When I use IMOVIE I can upload to iTunes no problem. However, when I save the movie to an external hard drive or my desktop. Quicktime will not open it. I am using quicktime 10.4. Also with the new upgrade to Yosemite, the
-
Be able to submit bug reports via LittleBigPlanet 2.
We all know that there's so many bugs and glitches out there in LittleBigPlanet 2, so how about an option to submit a bug report directly from the game? Who's with me?
-
Any way to control a Samsung H-series (2014) TV with a Z2?
I can do screen mirroring no problem, but every remote app I've tried won't connect (a Google search suggests that the H-series TVs don't allow IP control, or at least that the protocol has been locked down), and the Samsung app (Samsung Smart View 2
-
Serial number doesn't work on new iMac
I've transferred my verisonof Aperture to my new iMac. The software prmotps me for my serial number, but when I enter it, it tells me the 'serial number is not valid'. Does this mean I have to buy the software again?