Socket programming and thread
Hi all,
I am getting problem while reading or writing to a port.
we have two different thread for reading and writing, are they synchronize by itself or we have to make it explictly.
the error i get are either of these two:
1) java.io.EOFException
2) java.net.SocketException: Broken pipe
i am writing server and client which is thread based, i have implemented the biderectional ,first client writes to server. server reads from client first and then writes to client ,after server write client is not able to read data written by server. i am using the ObjectRead and Object Write methods of socket .
At client when i read it gives the following error java.io.StreamCorruptedException
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.canarys.web.pushlet.newClient.run(Client.java:93)
please help me out how to avoid this, the object i am using is serialised, if any of u need more clarification i will paste the code also
any help regarding this will be appreciated
Similar Messages
-
Server socket programming and thread
hello,
briefly this is what i have sought out to do : the server waits for the client indefinitely,upon a client requesting for service by writing a service id into the socket, a new thread of the type id as read by the server which is a sub-class of the Server (main-class) is exec'd.
the problem as i understand is that the client can send as much of data as it desires to the server and the thread can read the data it receives by the clients.the server(thread) fails to write reply to the client;eventhough out.write() is successful;the client is blocked in read() indefinitely.is it because of the thread which runs at a different port the client does not know and the server is not redirecting response to the client.
how do i read what the server(thread) writes onto the socket from the clients.thanks again,just check out this code please
public class Server extends Thread //create a multi-threaded server
/* *Creates a new instance of Server */
String serverAddr=CodeServer.ServerRun.SERVER_IP_ADDR;
int serverPortNum=CodeServer.ServerRun.SERVER_TCP_PORT;
ServerSocket sSock;
Socket cSocket;
int requestID=0;
boolean debug=true;
InputStream in =null;
OutputStream out=null;
Server ()
Server (Socket csocket)
this.cSocket = csocket;
/* start the server at specifed portNum */
private void initialise ()
try
//start the server at serverPortNum
sSock=new ServerSocket (serverPortNum);
catch (IOException ex)
ex.printStackTrace ();
/* console output of status of server */
if(debug==true)
System.out.println ("Server waiting @ "+sSock);
private void acceptRequest ()
try
this.cSocket=sSock.accept ();
if(debug==true)
System.out.println ("client socket @ "+cSocket);
catch (IOException ex)
ex.printStackTrace ();
private void readRequestID ()
/*step 1: determine the type of server before threading
*a request the the type of server got by the request ID
* number */
try
in =cSocket.getInputStream ();
requestID =in.read ();
out =cSocket.getOutputStream ();
if(debug==true)
System.out.println ("accross the client:"+requestID);
catch (IOException ex)
ex.printStackTrace ();
private void execThreadForRequest ()
/*step 2: after requestID is received on the socket.
*its time to decide the server to thread the control into.
switch(requestID)
case 1: //invoke the RegisterServer thread
new CodeServer.Core.RegistrationServer (this.cSocket).start ();
break;
case 2: //invoke the ListingServer thread
break;
case 3: //invoke the MessageTransferServer thread
break;
case 4: //invoke the CallSetupServer thread
break;
case 5: //invoke the DisconnectServer thread
break;
case 6: //invoke the ChangeUserStatusServer thread
break;
public void run ()
// client processing code here==super class does nothing here
public static void main (String args[]) throws Exception
Server s=new Server ();
s.initialise ();
/* start indefinitely the main server thread */
while (true)
/* accept() blocks the server for a request
a new request is put into a thread for processing */
s.acceptRequest (); //initialise the clientSocket
s.readRequestID (); //get the actual requested service
s.execThreadForRequest (); //start the actual server thread
/**registration service class;
*registers the IP address of the caller,callee and the status
*adds the caller to the hash table and updates status
class RegistrationServer extends Server
Socket cSocket;
InetAddress clientAddr;
DataInputStream inStream;
DataOutputStream outStream;
//Socket s=new Socket()
RegistrationServer (Socket cSocket)
this.cSocket=cSocket;
clientAddr =cSocket.getInetAddress ();
try
//init for reading status and custom message.
inStream =new DataInputStream (cSocket.getInputStream ());
outStream =new DataOutputStream (cSocket.getOutputStream ());
catch (IOException ex)
ex.printStackTrace ();
if(CodeServer.ROO.DEBUG==true)
System.out.println ("register server:"+cSocket
+" host ip:"+clientAddr.getHostName ());
public void run ()
int status=0;
String custMesg=null;
try
/* read the custom message */
if(inStream.available ()>0)
try
custMesg=inStream.readUTF ();
System.out.println (""+custMesg);
catch(EOFException e)
e.printStackTrace ();
else
custMesg="";
catch (IOException ex)
ex.printStackTrace ();
try
here is the problem, i found if i try reading accross the client
i only receive a junk value 81 always */
outStream.write(1); //write success
outStream.flush();
catch (IOException ex)
ex.printStackTrace ();
}and with the client GUI :thanks for the help.please do find time to help me out with a suggestion or two on this code. -
Socket Programming and Applets
Hello Everyone,
I am aiming to develop an application that would communicate with an Applet. I would like to know if this is possible and if there would be any security restrictions in between?
Thank youyou were running that your own machine, and what about java permission? how to handle that? suppose i have just jre installed and all permission disabled, how will your signed jar will run, there are many more things have to be done in that context.
for doing this one have to read a lot of things
http://java.sun.com/docs/books/tutorial/security/tour1/step2.html
no personal issue, just pointing out few area.
regards
Aniruddha -
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. -
Implementing sockets and threads in a jframe gui program
Hi, I am trying to find a solution to a problem I am having designing my instant messenger application.
I am creating listening sockets and threads for each client logged into the system. i want to know if there is a way to listen to other clients request from the main gui and then if another client tries to establish a connection with me for example, a thread is created for that client and then my chat gui opens automatically has soon has the other client sends his or hers first text message to me.
I am relatively new at socket programming has I am currently studying along this area. I know how to create threads and sockets but I am having trouble finding out a solution to my problem. Here is the code that I have done so far for the listening method from my main gui, and the thread class of what I have done so far.
listening socket:
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)
client_thread w;
try
w = new client_thread(serverSocket.accept(), jTextArea1);
Thread t = new Thread(w);
t.start();
catch(IOException x)
JOptionPane.showMessageDialog(null, "error, cannot start new thread", null, JOptionPane.ERROR_MESSAGE);
}thread class:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
* @author jonathan
public class client_thread extends Thread
//define new socket object
private Socket client_user = null;
private JTextArea textArea;
public client_thread(Socket client_user, JTextArea textArea)
this.client_user = client_user;
this.textArea = textArea;
public void run()
BufferedReader in = null;
PrintWriter out = null;
String error = "error has occured, messege was not sent";
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();
//display messege in textfield
out.println(messege);
textArea.append(messege);
catch (IOException e)
//error messege
JOptionPane.showMessageDialog(null, error, null, JOptionPane.ERROR_MESSAGE);
}Seems like all you need to do is create a new dialog for each socket that is established. Your current design looks like it will attempt to use the same textarea for all the sockets.
I would say in your thread class do the following:
MyConversationDialog dialog = new MyConversationDialog();
while(true)
//read messege sent by user
messege = in.readLine();
//display messege in textfield
out.println(messege);
dialog.setVisible (true);
dialog.addMessage (message);
} -
I have written a socket client and a socket server. The client sends a directory name and the server sends directory files and their content. The client asks for files every five seconds (it has to be made once every day, but for trials I have reduced the time), so I have written a thread to made the client sleep for that time. The problem appears after looping fifty or sixty times, when the socket, which does not die, stops making its work (files are not send any more). I really thank every answer.
Please be clear. What "stops work" the client or the server? Can you post the relevant code that is "looping fifty or sixty times"?
-
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) -
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. -
How to run a datagram socket client and server program
hi,
I am new to socket programming. I am following the tutorial of sun for socket programming...The link is
http://java.sun.com/docs/books/tutorial/networking/datagrams/clientServer.html
I have understood the concept, but the problem is i cannot run the program. I am using netbeans and i have created a package and stored the files QuoteServer,QuoteServerThread, QuoteClient in this package. How can i make the server program run first and then client program in netbeans
kindly help me
ThankyouI think you are trying to run both server and client
on one machine!!!
It is impossible, your server is blocking the port to
send packets, so you must run client on another
computer!!!It's not impossible to run a client and server on the same machine just for testing or as a demo. Just have the server listen on one port and the client use a different port.
No need to use 2 seperate computers. I've done it one computer before without a problem.
Nick -
RMI and Traditional network socket programming
Friends,
Please help me
What is the advantage of RMI over socket programming ?you may need to refer to a good RMI book for having a detailed answer. Since they are quite a few of em.
-
Problem with socket programming(Vista)
I'm not sure if this has something to do with windows vista.
I wrote simple echo client and server programs and the client program contains these lines
String hostname="172.16.54.22"; //My comp's IP
int portNo=6666;
mySocket=new Socket(hostname, portNo);
Now the problem is that the client program is able to communicate with the server only when I run both of them in xp machines or if I run the server in vista and client in xp. The client is not able to connect to the server when both the client and server are running in a vista machine or if the server is running in xp and client in vista.
It'd be nice if any of you could throw some light on this issue.
PS:
It doesn't work even if I turn the firewall off
The programs work well when I give hostname="localhost" or hostname="127.0.0.1"
Here are my programs
//EchoClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class EchoClient
public static void main(String args[])
String hostname="172.16.54.25"; //My ip address
int portNo=6666;
//if(args[1]
//PrintWriter out=null;
Socket mySocket=null;
BufferedReader networkIn=null;
BufferedReader userIn=null;
PrintWriter sockOut=null;
try
mySocket=new Socket(hostname, portNo);
networkIn=new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
userIn=new BufferedReader(new InputStreamReader(System.in));
sockOut= new PrintWriter(mySocket.getOutputStream());
System.out.println("Connected to Echo Server\n");
System.out.println("Enter a series of lines (\"end\" to exit)\n");
while(true)
String myLine=userIn.readLine();
// System.out.println(myLine);
if(myLine.equals("end"))
break;
sockOut.println(myLine);
sockOut.flush();
System.out.println(networkIn.readLine());
catch(IOException exc)
System.err.println(exc);
finally
try{
if(networkIn!=null) networkIn.close();
if(sockOut!=null) sockOut.close();}
catch(IOException exc){ }
EchoServer.java
//EchoServer.java
import java.io.*;
import java.net.*;
class EchoServer
public static void main(String args[])
int portNo=6666;
ServerSocket serverSock=null;
try
serverSock=new ServerSocket(portNo);
System.out.println("Echo Server Started\n\n");
while(true)
Socket clientSock=serverSock.accept();
new Thread(new EchoServerThread(clientSock)).start();
catch(IOException exc)
System.err.println(exc);
EchoServerThread.java
//EchoServerThread.java
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoServerThread implements Runnable
public Socket clientSock;
EchoServerThread(Socket sock)
clientSock=sock;
public void run()
System.out.println("\nAccepted Connection from a Client");
try{
BufferedReader in=new BufferedReader(new InputStreamReader(clientSock.getInputStream()));
BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out= new PrintWriter(clientSock.getOutputStream());
/*In sockIn=new In(clientSock);
Out sockOut=new Out(clientSock);*/
String str;
while((str=in.readLine())!=null)
out.println(str);
out.flush();
System.out.println("Closing Connection from a Client");
out.close();
in.close();
catch(IOException exc)
System.err.println(exc);
Sorry everyone but I'd been giving a wong IP address thinking it's my own. The problem's solved.
Thanks for the response Peter. -
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. Thanksupdate:
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... -
Sharing socket object between threads - Is any sync required?
For example, a thread receives (listens) datagram packets at incoming socket and forwards them downstream through another datagram socket. Another thread listens packets at this second socket and forwards the data via the first socket. It is possible that two threads invoke methods of the same socket (one is receiveng while another is sending). This situation is not described in the DatagramSocket manual. I beleive there is underlying synchronization at the OS kernel level. Can I relay on it? Thanks.
I expected some critics for using old plain sockets instead of nio :)You should use NIO if you have hundreds of connections. If you have a small number of connections and want a simple implementation use blocking IO as you have.
If you can have different
threads reading or writing at once eg two readingor
two writing then you need to use synchronisation.Shouldn't this be stated by the API designers somewhere?It is probibly covered in a tutorial or example somewhere.
You have a different input and output stream. There is a lock on each. This is your best hint.
Theoretically, nothing prohibits sending UDP packets in race conditions.
In fact, this is what my program
does - it respondes to different clients using one
(server) datagram socket. The responses are produced
by multiple threads. I suppose that java does not
involve any state variables; thus, beleive that the
system can accomplish the synchronisation unnecesary
at the application level.That depends on how you build and send your messages. If each part of the message can be sent in one hit and the order does not matter you are fine.
If you have a single object shared between threads, then all members are shared, not just static variables. -
Actually my client and server ,both are running on same m/c.
client code is
Socket s1;
try{
s1 = new Socket("localhost",5678);
catch(Exception e){}
Server Code is
ServerSocket serverSocket = new ServerSocket(port);
while(true) {
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
new Thread(new SocketNode(socket)).start();
where constructor for SocketNode is like this :-
public
SocketNode(Socket socket) {
this.socket = socket;
try {
ois = new ObjectInputStream(socket.getInputStream());
catch(Exception e) {
cat.error("Could not open ObjectInputStream to "+socket, e);
It throws exception in opening object input stream.
Could anybody suggest the possible reasons for it.
error is something like this :-
ERROR [main] Logger.SocketNode (<init>:35) - Could not open ObjectInputStream to Socket[addr=/127.0.0.1,port=1800,localport=5678]
java.net.SocketException: Connection reset by peer: JVM_recv in socket input stream read
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Logger.SocketNode.<init>(SocketNode.java:32)
at Logger.SocketServer.main(SocketServer.java:40)
I will be really thankful, if anybody can help in this regardsHi Neetika,
Your error is telling that
your client program has
teminated before server
could create an ObjectInput
Stream. So, for this you KEEP
your client program
alive for some time( So that
socket object in client side
is not swapped out by Garbage
collector ).
and then you will not get above error.
cheers!
Maybe you are looking for
-
Hi gang, I created two Apple Loops from a couple audio regions in my session so I could adjust the tempo. Only one of the regions succesfully converted and imported to an apple loop, but now my entire Apple Loop library is gone and I have have those
-
How to call Web Services (with javascript) in a view load event ?
Hello to the expert community, I'm looking for a piece of javascript code allowing to call Web Services in a view load event ? Any ideas will be really appreciated. Regards. Have a nice week.
-
Date/locale problems; first day of week / browser language
Hi, I've been trying to create an event calendar PL/SQL portlet. My problem is that it reacts to browser language or something, so it goes all screwy when viewed with browsers in another language. How can I force my portlet to be finnish and finnish
-
Help with relational database model
Hi everyone, How will a database model look like if you have one program that writes to the database and one program that reads from it. The database tables consist of customer orders. Regards Ardalan
-
Cisco 4710 ACE syslogs generating issue
I have 4710 ACE load balancer with three virtual contexts, i have configured the three contexts with the syslog configuration to send the logs to a syslog server as below: logging enable logging trap 5 logging buffered 7 logging host 10.x.x.x udp/514