Socket constructor problems
I have a moderate amount of experience with Java, but am new to network programming. I am using the Socket class, but the client stalls at the line containing the Socket constructor. I have been all over the web, and have checked numerous code examples, but my code seems to check out. Here is the constructor and relevant code:
final int LOAD_PORT = 7778;
InetAddress addr = InetAddress.getByName("127.0.0.1");
Socket socket = new Socket(addr, LOAD_PORT);
I am trying to just get this to work with both the client and the server running on my machine to start with. I have some TextArea.append statements interspersed so that I know which line stalls, and the last .append statement that works is just before the Socket constructor line.
If anyone might know what my problem is, please respond.
I tried that and about a million other combinations.
I finally figured the problem out about a week ago...
I needed to upgrade to SDK 1.4.0 from SDK 1.3.1. I tested this program out on a system using 1.4 and it worked fine with no modifications at all. Then I went back to a 1.3 system, it didn't work, I downloaded and installed 1.4, tried it again, and it worked like a charm.
Thanks for the reply, though,
Tim
Similar Messages
-
Socket Listening problem in Netbeans
Hello All
I am using "Netbeans Version 6.8" and i am making a client chat application. and it is not receiving messages from the Server Application. the code is posted bellow, Can any body rectify or solve the problem.
* To change this template, choose Tools | Templates
* and open the template in the editor.
* ChatClient.java
* Created on May 7, 2010, 4:23:42 PM
package chatclient;
import java.io.*;
import java.net.*;
import java.util.*;
//import java.awt.*;
* @author Adeel
public class ChatClient extends javax.swing.JFrame {
/** Creates new form ChatClient */
Socket s;
BufferedReader br;
BufferedWriter bw;
List list;
public ChatClient() {
initComponents();
try{
/*Put the current IP address for current machine
if you didn't have an actual server and clients
if you have an actual server and clients put the client IP address*/
//// s = new Socket("localhost",100);
s = new Socket("127.0.0.1",100);
br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
Thread th;
th = new Thread();
th.start();
}catch(Exception e){}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Send");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Logout");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap())
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String chatText;
String newline = "\n"; // for new line in jTextArea
chatText=jTextField1.getText();
jTextArea1.append(chatText + newline);
try{
bw.write(chatText);
bw.newLine();
bw.flush();
}catch(Exception m){}
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatClient().setVisible(true);
public void run()
try{s.setSoTimeout(1);}catch(Exception e){}
while (true)
try{list.add(br.readLine());
}catch (Exception h){}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}Waiting for your response
Regards
Adeelthank you for your feedback,
but it is still not showing any problem or throwing any Exception. The sending code is working properly but it is not listening/receiving any message from server application. i think, there is a void run() method which is not reacting properly.. i have commented that area in the code.. other rest of code is 100% working, i have checked that...
There are 2 run() methods in the code, Can you please check it for me, may you understand/rectify the problem why it is not listening.
* To change this template, choose Tools | Templates
* and open the template in the editor.
* ChatClient.java
* Created on May 7, 2010, 4:23:42 PM
package chatclient;
import java.io.*;
import java.net.*;
import java.util.*;
//import java.awt.*;
* @author Adeel
public class ChatClient extends javax.swing.JFrame {
/** Creates new form ChatClient */
Socket s;
BufferedReader br;
BufferedWriter bw;
List list;
public ChatClient() {
initComponents();
try{
/*Put the current IP address for current machine
if you didn't have an actual server and clients
if you have an actual server and clients put the client IP address*/
//// s = new Socket("localhost",100);
s = new Socket("127.0.0.1",100);
br = new BufferedReader(new InputStreamReader(
s.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
Thread th;
th = new Thread();
th.start();
}catch(Exception e){
e.printStackTrace();
/** 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.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Send");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
jButton2.setText("Logout");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap())
pack();
}// </editor-fold>
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String chatText;
String newline = "\n"; // for new line in jTextArea
chatText=jTextField1.getText();
jTextArea1.append(chatText + newline);
try{
bw.write(chatText);
bw.newLine();
bw.flush();
}catch(Exception m){
m.printStackTrace();
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
///////////////////////////////////////////// 2nd RUN METHOD, ///////////////////////////////////////////
public void run() {
new ChatClient().setVisible(true);
//////////////////////////////////////////// 2nd RUN METHOD, //////////////////////////////////////////
///////////////////////////// RUN METHOD, which may have prob /////////////////////////////
public void run()
try{s.setSoTimeout(1);}catch(Exception e){
e.printStackTrace();
while (true)
try{list.add(br.readLine());
}catch (Exception h){}
///////////////////////////// RUN METHOD, which may have prob /////////////////////////////
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}Thanks again for you attention.
Regards
Adeel -
Hi All:
We all know that "Socket(String host, int port)" create a client socket which connecting to
the target host : port
however, which local port does it connect from? I guess it must be a random port from list of
available ports. but how can we find out which port is currently been used?
I thought another constructor Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
might help. but the following code :
" Socket connection = new Socket("www.google.com", 80, InetAddress.getByName("localhost"), 0);"
doesn't work either. can anyone spot the problem please0 means ANY currently available port, what's wrong with choosing 0 to be the port number?
just because is not documented on the Java documentation? read http://books.google.co.uk/books?id=NyxObrhTv5oC&dq=java+network+programming&pg=PP1&ots=1d9JyFUpRY&sig=HPm47jAWjRHrMpZw0UTG2nM86bA&hl=en&prev=http://www.google.co.uk/search?hl=en&q=java+network+programming&btnG=Google+Search&sa=X&oi=print&ct=title&cad=one-book-with-thumbnail#PPA281,M1
before even recommend your so-called better book. by the way it was a firewall issue.I 'v got it solved now.
may be "didn`t work" is not efficient word to explain things, but it is better then
someone wrote down full of c.r.a.p, without saying anything useful at all.
I don`t understand why my question doesn`t make any sense. choosing random port at runtime rather then
giving a specific number, is a common programming technique, I thought it making a GREAT sense.
Edited by: Shanyangqu on Jan 21, 2008 3:38 AM -
BT Faster slow - lack of master socket the problem...
My new BT Faster FTTC broadband is not delivering the promised speed, and I hoped someone here might have some knowledgable suggestions.
I was promised a speed of 12-18Mbps down, but it's actually delivering (on first day) just over 8Mbps.
(The promised speed matches that returned by the dslchecker for my number, and the actual speed has been measured using speedtest.net as well as BT Wholesale speedtest).
Wondering if at least part of the problem is that the premises doesn't have a proper master socket. The only live sockets are "extension" sockets. I've plugged into the one of these nearest the small BT junction (?) box just inside the house to try to optimise speed.
I did warn BT that the house didn't have a proper master socket and requested an engineer install for this reason, but they insisted I try a self install of the HH5 and "see how it goes". I wonder if the speed wouldn't be improved to something closer to that promised if there was a master socket installed (an NTE5 or even a SSFP Infinity).
Any advice on how I should proceed and/or whether I should go back to BT to request they install a master socket? Any and all help would be much appreciated!
In case of any help, here are the hub stats from the "Helpdesk" view:
Product name: BT Home Hub
Serial number:
Firmware version: Software version 4.7.5.1.83.8.173.1.6 (Type A) Last updated Unknown
Board version: BT Hub 5A
VDSL uptime: 0 days, 03:02:33
Data rate: 1257 / 9395
Maximum data rate: 1257 / 8953
Noise margin: 6.1 / 6.0
Line attenuation: 0.0 / 35.2
Signal attenuation: 0.0 / 27.6
Data sent/received: 39.0 MB / 229.6 MBThanks for the reply John. The checkers are still giving me the same results as yesterday, screengrabs now attached:
1. Product name: BT Home Hub
2. Serial number: +
3. Firmware version: Software version 4.7.5.1.83.8.204 (Type A) Last updated 28/02/15
4. Board version: BT Hub 5A
5. DSL uptime: 0 days, 00:33:28
6. Data rate: 1261 / 9260
7. Maximum data rate: 1269 / 9293
8. Noise margin: 6.2 / 6.1
9. Line attenuation: 14.9 / 36.5
10. Signal attenuation: 14.9 / 28.6
11. Data sent/received: 13.4 MB / 188.7 MB -
Servlet Server Socket Communication problem
Hi
Iam having this problem ...when I read data in server line by line it works but when I try to read byte by byte server hangs. This is my code
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
//it works fine when i do
String strLine = in.readLine();
//but hangs when I do like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r = in.read();
while(r != -1)
baos.write(r);
r = in.read();
I am sending data from the client socket as
out = new PrintWriter(addArtSocket.getOutputStream(), true);
I just do out.println to send data.
Is there something wrong that I am doing?
Thanks
vinithahi,
basically, I suggest that you have the communication
channel in the same type between two ends. For example,
if you decide to connect two side byt Stream, you just
apply your code in the sort of Stream for I/O.
If you decide to connect two sides by Reader/Writer, you
apply your code in the sort of Reader/Writer for I/O.
Don't mix them up. Although I don't know what may
happen. For example, you want to pass an Object
between two ends, you could use ObjectInputStream/
ObjectOutputStream pair on two sides. Don't put
ObjectInputStream in one side and talk to one sied
which write data by other OutputStream filteer but
not ObjectOutputStream .
You may find something interesting.
good luck,
Alfred Wu -
Constructor problem with super keyword
When I try to compile this class, I get 1 error:
C:\Program Files\Xinox Software\JCreatorV3\MyProjects\FixedDiameterCircle.java:6: cannot resolve symbol
symbol : constructor CircleGUI (int)
location: class CircleGUI
super(100);
^
1 error
class FixedDiameterCircle extends CircleGUI
FixedDiameterCircle()
super(100);
}//end FixedDiameterCircle()
public void setDiameter(int d)
}//end class FixedDiameterCircle
---------Here's the CircleGUI.java-------
import javax.swing.*; //import Swing components
import java.awt.*; //import awt components
import java.awt.event.*; //import event handlers
public class CircleGUI implements ActionListener
JTextField diameter = new JTextField(3); //text field for first name
JTextField color = new JTextField(5); //text field for last name
JButton button = new JButton("Draw"); //update button
JPanel panel = new JPanel(); //panel for frame content pane
JFrame frame = new JFrame("Draw"); //frame for window + title
public CircleGUI()
panel.add(new JLabel("Diameter")); //add a label to panel
panel.add(diameter); //add first to panel
panel.add(new JLabel("Color")); //add another label to panel
panel.add(color); //add a last to panel
button.addActionListener(this); //add a click listener to button
panel.add(button); //add button to panel
frame.setContentPane(panel); //set panel as frame's content
frame.setSize(120, 120); //set frame size (width, height)
frame.setVisible(true); //make frame visible
}//end CircleGUI()
public void actionPerformed(ActionEvent e)//executed when button is clicked
int d = Integer.parseInt(diameter.getText()); //get diameter
Circle circle; //declare Circle variable
if(color.getText().length() == 0) //if no color entered in field
{ //use JColorChooser below
Color rgb = JColorChooser.showDialog(frame, "Choose a Color", null);
if(rgb != null) //if Color rgb chosen
circle = new Circle(d,rgb); //instantiate Circle from Color
}//end if(color...
else
String c = color.getText(); //get color String
circle = new Circle(d,c); //instantiate Circle from String
}//end else
}//end actionPerformed()
public static void main(String[] args) //main method
CircleGUI cGUI = new CircleGUI(); //instantiate CircleGUI
}//end main()
}//end class CircleGUI
What's the problem?CircleGUI does not have a constructor that takes an int. You need to either add this to CircleGui:public CircleGui(int diameter) { /* do stuff */ } or just cal super() instead of super(int). Which one is better is left as an exercise for the reader.
-
I'm starting a server with the following code
Semaphore semaphore = new Semaphore(maxConcurrentConnections);
final ServerSocket serverSocket = new ServerSocket(Constants.NET_APPLET_PORT);
while (true) {
semaphore.acquire();
final Socket socket = serverSocket.accept();
final Runnable task = new ConnectionHandler(socket, userDatabase, messageDatabase);
final Thread thread = new Thread(task);
thread.start();
semaphore.release();
and then try to connect using
socket = new Socket(Constants.NET_HOST_NAME, Constants.NET_APPLET_PORT);
But, when I try to connect there's just a few seconds delay and the I get a ConnectionException: Connection timed out error. Any idea what could be the problem? Thanks / JoachimIf it is to any help, the same thing happens when I
try to connect from the server.Do you have a firewall? -
Hi
I have this problem,sometimes i manage to connect to a server using sockets but sometimes it does not want to connect.cany please tell me what do you think the problem could be since sometimes it manages to connect sometimes.
PlsAre u behind firewall ?
Is it in intranet or internet ?
when ur application fails to connect, did u check ur network connectivity via ping or sothingelse ?
regards,
Shahnaz. -
I am getting the following error
The applet orderproc.NewUser does not have a public constructor orderproc.NewUser()
I dont understand this as the rest of my applets have similar code but dont get this problem. Can any of you nice people out there help. Here is my code:
package orderproc;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.net.URL;
import java.sql.*;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
public class NewUser extends JApplet implements ActionListener {
JPanel westPanel;
JPanel eastPanel;
JLabel lblFirstName, lblLastName, lblPassword, lblUserName;
JTextField txtFirstName,txtLastName,txtUserName, txtPassword;
JButton btnSubmit, btnBack, btnCancel;
String FN,LN,PS,UID;
public NewUser()
GridBagLayout gbl;
GridBagConstraints gbc;
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
westPanel = new JPanel();
westPanel.setLayout(gbl);
eastPanel = new JPanel();
eastPanel.setLayout(gbl);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(westPanel, BorderLayout.CENTER);
getContentPane().add(eastPanel, BorderLayout.SOUTH);
lblFirstName = new JLabel("First Name: ");
lblLastName = new JLabel("Last Name: ");
lblPassword = new JLabel("Password: ");
lblPassword = new JLabel("User Name: ");
txtFirstName = new JTextField(15);
txtPassword = new JTextField(15);
txtLastName = new JTextField(15);
txtUserName = new JTextField(15);
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(this);
eastPanel.add(btnSubmit);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(this);
eastPanel.add(btnCancel);
btnBack = new JButton("<<<<Back");
btnBack.addActionListener(this);
eastPanel.add(btnBack);
gbc.anchor = GridBagConstraints.NORTH; // Align labels
gbc.gridx = 1;
gbc.gridy = 1;
gbl.setConstraints(lblFirstName, gbc);
westPanel.add(lblFirstName);
gbc.gridx = 1;
gbc.gridy = 2;
gbl.setConstraints(lblLastName, gbc);
westPanel.add(lblLastName);
gbc.gridx = 1;
gbc.gridy = 3;
gbl.setConstraints(lblPassword, gbc);
westPanel.add(lblPassword);
gbc.gridx = 1;
gbc.gridy = 4;
gbl.setConstraints(lblUserName, gbc);
westPanel.add(lblUserName);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 2;
gbc.gridy = 1;
gbl.setConstraints(txtFirstName, gbc);
txtFirstName.setEditable(true);
westPanel.add(txtFirstName);
gbc.gridx = 2;
gbc.gridy = 2;
gbl.setConstraints(txtLastName, gbc);
txtPassword.setEditable(true);
westPanel.add(txtLastName);
gbc.gridx = 2;
gbc.gridy = 3;
gbl.setConstraints(txtPassword, gbc);
txtPassword.setEditable(true);
westPanel.add(txtPassword);
gbc.gridx = 2;
gbc.gridy = 4;
gbl.setConstraints(txtUserName, gbc);
txtUserName.setEditable(true);
westPanel.add(txtUserName);
public void actionPerformed(ActionEvent ae) // Action event handling
if(ae.getSource() == btnBack)
setVisible(false);
else if(ae.getSource() == btnCancel)
txtFirstName.setText(null);
txtPassword.setText(null);
txtLastName.setText(null);
txtUserName.setText(null);
else if(ae.getSource() == btnSubmit)
FN = txtFirstName.getText();
LN = txtLastName.getText();
PS = txtPassword.getText();
UID = txtUserName.getText();
try
//connect to database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Drivers loaded");
String url = "jdbc:odbc:wms";
Connection con = DriverManager.getConnection(url,"root","");
System.out.println("Connection established");
Statement stmt = con.createStatement();
System.out.println("Statement created");
ResultSet res = stmt.executeQuery("INSERT INTO login (FirstName, LastName, Password, UserName) VALUES ('"+FN+"','"+LN+"', '"+PS+"','"+UID+"')");
con.close();
catch(Exception e)
txtFirstName.setText(null);
txtLastName.setText(null);
txtPassword.setText(null);
txtUserName.setText(null);
public void init()
NewUser myNewUser = new NewUser();Why don't you just implement the RSAPrivateKey and RSAPublicKey interfaces?
-
UDPClient socket.receive() problem
I have a slight problem.... while receiving the packets.....
/*** DECLARE AND INSTANCIATE DATAGRAM TO RECEIVE ***/
/* buffer for holding the incoming datagram*/
byte[] buffer = new byte[size];
DatagramPacket reply[] = new DatagramPacket[size];
start = System.currentTimeMillis();
/*** SEND DATAGRAM PACKETS (THIS SECTION WORKS FINE)***/
for(counter = 0; counter < size; counter++)
request[counter] = new DatagramPacket(m, m.length, aHost, serverPort);
aSocket.send(request[counter]);
System.out.println("Sent all");
/*** RECEIVE DATAGRAM PACKETS ( PROBLEM SECTION )***/
for (Getcount = 0; Getcount < size ; Getcount++)
System.out.println("Receving " +Getcount);
reply[Getcount] = new DatagramPacket(buffer, buffer.length);
System.out.println("got pack in array");
SPECIFICALLY PROBLEM IS HERE >>>>aSocket.receive(reply);
HOW DO I receive the package?
I cannot try to recieve individual because I doono which one is going to show up first... so I cant put in a lopp saying that aSocket.receive(reply[Getcount]); also I cannot get it using aSocket.receive(reply);
because the receieve needs a datagram packet.....
System.out.println("Received by socket");
end = System.currentTimeMillis();
difference = end - start;
System.out.println("Reply: " + new String(reply[0].getData()));
System.out.println("Difference in time was "+difference+" milliseconds");I am setting the size as 100 in the arg[0] but the problem is that
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.*;
public class UDPClientTest
public static void main(String args[])
DatagramSocket aSocket = null;
try
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789;
int counter;
int Getcount;
/*** SET ARRAY SIZE FROM COMMAND PROMPT ***/
int size = Integer.parseInt(args[0]);
byte[] m = new byte[size];
/*** FILL ARRAY WITH RANDOM NUMBERS ***/
for(int count = 0; count < size; count ++)
m[count] = (byte)(Math.random()*1000);
/*** INITIALIZE EVERYTHING HERE (BEFORE TIMER STARTS COUNTING TIME) ***/
/*** DECLARE AND INSTANCIATE DATAGRAM TO SEND ***/
DatagramPacket request[] = new DatagramPacket[size];
/*** DECLARE AND INSTANCIATE DATAGRAM TO RECEIVE ***/
/* buffer for holding the incoming datagram*/
byte[] buffer = new byte[10000];
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
/*** VARIABLES FOR TIMERS ***/
long start = 0, end = 0, difference = 0;
/*** START TIMER (USING SYSTEM TIMER NOT DATE OBJECT FOR MORE ACCURACY)***/
start = System.currentTimeMillis();
/*** SEND DATAGRAM PACKETS ***/
for(counter = 0; counter < size; counter++)
request[counter] = new DatagramPacket(m, m.length, aHost, serverPort);
aSocket.send(request[counter]);
System.out.println("Sent all");
/*** RECEIVE DATAGRAM PACKETS ***/
>>>>>>>>>PROBLEM BELOW<<<<<<<<<<<<<<<
aSocket.setSoTimeout(1000000000);
/****PROBLEM: EVEN THOUGH I HAVE SIZE WHICH IS 100 when I start program in arg[0] the program just starts from 99 but stops at 17 and prints what I have displayed after code and waits ****/
while(--size >= 0)
reply = new DatagramPacket(buffer,buffer.length);
try{
System.out.println(size);
aSocket.receive(reply);
System.out.println("After receive");
} catch(SocketException e){System.out.println("Socket Exception "+e.getMessage());}
/*** END TIMER ***/
end = System.currentTimeMillis();
difference = end - start;
System.out.println("Reply: " + new String(reply.getData()));
System.out.println("Difference in time was "+difference+" milliseconds");
catch (SocketException e){System.out.println("Socket: " + e.getMessage());}
catch (IOException e){System.out.println("IO: " + e.getMessage());}
finally {if(aSocket != null) aSocket.close();}
}.........STARTS WITH 99 and prints this below
After receive
27
After receive
26
After receive
25
After receive
24
After receive
23
After receive
22
After receive
21
After receive
20
After receive
19
After receive
18
After receive
17
then it justs waits............
Please help me......... -
I am using multi threading with socket programming. One thread uses socket's output stream to send the data and the other thread keeps waiting for the data to arrive from that socket's input stream.
Now when the readLine or readObject is excuting on the receiver thread it will be blocked untill data arrives. In which case sending thread will not be able to send the data.
Now is there any way to make the readLine or readObject method non blocking?
Please advise ASAP
thnksBelow is an example of a simple blocking multi-threaded client program that connects to google. I don't believe I've ever experienced a problem like you're describing before while dealing with Java sockets; perhaps this will give you an idea about what's going wrong. One thread reads from stdin, the other (the main-thread of execution) reads from the socket and writes to the screen.
java Test
Then do a GET request to the HTTP server:
"GET / HTTP/1.0"
Then press return again and watch it send you google's root page.
import java.net.*;
import java.io.*;
class Test
Test()
try
Socket mySocket = new Socket("www.google.com", 80);
BufferedReader myReader;
final BufferedWriter myWriter;
myWriter = new BufferedWriter(new OutputStreamWriter(mySocket.getOutputStream()));
Thread myThread = new Thread()
public void run()
System.out.println("here");
try
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
String str;
while((str = inputReader.readLine()) != null)
myWriter.write(str);
myWriter.write("\n");
myWriter.flush();
catch(IOException e)
System.err.println("Error reading from stdin.");
System.exit(-1);
myThread.start();
System.out.println("there");
myReader = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
String str;
while((str = myReader.readLine()) != null)
System.out.println(str);
catch(IOException hostExcep)
System.out.println("Host terminated the connection!");
hostExcep.printStackTrace();
public static void main(String args[])
new Test();
} -
Hi,
I am reading a response from the Socket by using InputStream and BufferedReader object. Reading it byte by byte. But as my response data ( bytes) is very large (6000- 7000 bytes). The reading time is almost 5-6 minutes.
As i dont know the socket inputstreams size ( no of bytes) i can't use readFully() method of DataInputStream becoz byte array size is to be specified . If the array size > reponse size, it throws EOF exception,
So my problem is that reading the response should be fast . Can you please tell any way of reading the response fast or knowing the socket inputstreams size in prior before reading it .
Awaiting your reply,
Regards,
Prakash.balramprakash wrote:
Hi,
I am reading a response from the Socket by using InputStream and BufferedReader object. Reading it byte by byte. BufferedReaders read text (16-bit char) not bytes.
But as my response data ( bytes) is very large (6000- 7000 bytes). This isn't very large unless you network is very slow. Even with 1 Mb broadband this would take 0.07 seconds to download. On a dial modem it would take 1.5 second.
The reading time is almost 5-6 minutes. You have a serious problem with your setup. Even reading one character at a time (which is the slowest way to do this) it shouldn't take anywhere near that long.
Perhaps you don't know when the response ends so you ware waiting for a disconnect or the connection to timeout.
As i dont know the socket inputstreams size ( no of bytes) i can't use readFully() method of DataInputStream becoz byte array size is to be specified If you can change the format, you can send the size before you send the data and the reader know how much data to expect.
So my problem is that reading the response should be fastSend the size with the response. Don't use BufferedReader if you have binary data. (e.g. byte data) It it should take about 7 ms to load on a 10 Mb connection.
BTW: if you are opening a new connection each time it can take about 20 ms to establish, so the time to download the response is small in this case. -
I think I'm being really dense here but for the life of me, I can't get this code to work properly. I am trying to build a NIO socket server using JDK 1.4.1-b21. I know about how the selector OP_WRITE functionality has changed and that isn't my problem. My problem is that when I run this code:
if (key.isAcceptable()) {
System.out.println("accept at " + System.currentTimeMillis());
socket = server.accept();
socket.configureBlocking(false);
socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
if (key.isWritable()) {
System.out.println("write at " + System.currentTimeMillis());
if (key.isReadable()) {
SocketChannel client = (SocketChannel)key.channel();
readBuffer.clear();
client.read(readBuffer);
System.out.println("read at " + System.currentTimeMillis());
}the isWritable if statement will always return (which is fine) and the isReadable if statement will NEVER return (which is most certainly NOT FINE!!). The readBuffer code is there just to clear out the read buffer so isReadable is only called once per data sent.
This SEEMS to be a bug in how the selector works? I would expect to see isReadable return true whenever data is sent, but that is not the case. Now here is the real kicker ;) Go ahead and change this line:socket.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);to this:socket.register(selector, SelectionKey.OP_READ);And now it appears that isReadable is running as expected?! To let people run this code on their own, I have uploaded a copy of the entire java file here:
http://www.electrotank.com/lab/personal/mike/NioTest.java
Please forgive the code, it's just the smallest test harness I could make and much of it is lifted from other posts on this forum. You can test this by using Telnet and connecting to 127.0.0.1:8080. You can test the isReadable piece by just typing in the Telnet window.
Someone else has listed something as a bug in the Bug Parade, but the test case is flawed:
http://developer.java.sun.com/developer/bugParade/bugs/4755720.html
If this does prove to be a bug, has someone listed this already? Is there a nice clean workaround? I'm getting really desperate here. This bug makes the NIO socket stuff pretty unusable. Thanks in advance for the help!!
Mike Grundvig
[email protected]
Electrotank, Inc.I'm not sure that a key will ever return with more than one operation bit selected. I expect that the selector simply puts the key into the selected set as soon as it sees any one of the interestedOps that match the current state.
The general problem you are having, it seems, is that isWritable(), in many cases, will constantly return true for a low volume socket. This being the case, the only solution I see is to either deal with output with blocking calls or to dynamically change your interestedOps when there is data to write. That's what I did. I don't know yet how well it will scale. This is certainly not a bug, the application must deal with it. Perhaps it would be nice to have some kind of interface, like "SelectionKeyAttachment" and have the SelectionKey.attach() method take one of those. The SelectionKeyAttachment interface could implement something like isWritable(), isReadable(), isAcceptable() so that the Selector can also invoke the callback before putting it into the selected set. I haven't really thought this through, just initial thoughts. -
Instantiation attempted on a non-constructor problem
Hi,
I've got the following error in my application: "TypeError: Error #1007: Instantiation attempted on a non-constructor".
I've created a class that represents a 2D Vector. But when I instanciate it inside another class, I get this error.
Here is a little piece of code of my problem:
public class Player extends MovieClip {
private var position:Vector = new Vector();
public function Player() {
// constructor code
public class Vector {
public var xValue:Number;
public var yValue:Number;
public function Vector() {
// constructor code
xValue = 0;
yValue = 0;
These 2 classes are in separated files. The Player's class is a Movie Clip in the library, while Vector's class is just a class file. What can I be doing wrong?Vector is a native top level class in AS3.
-
Applet Socket permission problem
Heloo I made an applet which gets the content of web . like if i pass the www.yahoo.com to applet it must read all the html coding of yahoo page .my code is perfect with the desktop application but when i run it with applet then it gives the socket permission error i search all where but i havent found any solution i tried to edit policy file but still found the same error kindly help me how to get rid from this error thanks and below is my code sample
Applet code:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.security.Permission;
public class Apple extends JApplet implements ActionListener{
Container c;
JTextField uf=new JTextField(30);
JTextArea tarea=new JTextArea(600,600);
JButton b=new JButton("Get Content");
JButton bb=new JButton("Clear");
URL u;
JScrollPane sp=new JScrollPane();
InputStream is = null;
DataInputStream dis;
String s;
public void init(){
JOptionPane.showMessageDialog(null,"hello world");
c=new Container();
JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
c=this.getContentPane();
uf.setText("http://www.yahoo.com");
c.setLayout(new FlowLayout(FlowLayout.LEFT));
sp.add(tarea);
c.add(new JLabel("Enter Your Url"));
c.add(uf);
c.add(b); c.add(bb);
c.add(new Label("EXAMPLE: http://www.rentacoder.com"));
b.addActionListener(this);bb.addActionListener(this);
c.add(tarea);
public void actionPerformed(ActionEvent ae){
if( ae.getSource()==b){
JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
down();
if( ae.getSource()==bb){
tarea.setText("");
public void down(){
try{
System.out.println("1");
String uu=uf.getText()+":80";
u = new URL(uf.getText());
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
String str;int k=0;int l=50;
while ((s = dis.readLine()) != null) {
tarea.append(s+"\n");
k++;
if(k==l){
JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
l=2*k;
}is.close();
} catch (MalformedURLException e) {JOptionPane.showMessageDialog(null,"e"+e);
} catch (IOException e) {JOptionPane.showMessageDialog(null,e);
HTML CODE :
<applet code="Apple.class" width="300" height="300">
</applet>The applet should be able to connect to the host it came from but I think you
have to connect to the same port as well (not really sure about that).
You can either have the consumers of your applet set up a policy for your applet
or you sign the applet.
Signing applets:
http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
second post and last post for the java class file
http://forum.java.sun.com/thread.jsp?forum=63&thread=409341
4th post explaining how to set up your own policy with your own keystore
Java security configuration (according to me):
1. Signing, good for Internet published applets. The user will be asked if he or she trusts
the applet and when yes or allways is clicked the applet can do whatever it wants. This
is the default setting of the SUN jre and can be compared with IE setting that askes the
user about downloading and running ActiveX controls from the Internet security zone.
2. Setting up a policy. Good for people who disabled asking the user about signed
applets (like companies that are worried this could cause a problem). it is possible
to provide multiple java.policy files in the java.security, a company could put a .policy file
on the Intanet and have all jre's use this by adding this URL to the java.security.
When a policy needs to be changed the admin only has to do this is the file on the
Intranet.
A specific user can have a policy in their user.home to set up personal policies (to be
done by Administrators).
A policy file can use a keystore to be used in a signed by policy. For example "applets
that are signed by SUN can access some files on my machine). It can allso be used
to identify yourselve, when making an SSL connection the keystore can be used as
the source of your public key.
Maybe you are looking for
-
Quicktime codec for fcp files?
is there a way to view newer fcp files with out purchasing fcp? any iMovie plugins or quicktime or quicktime pro codecs available? I have fcp 6.0.6 on an old G5 dual processor runing Tiger 10.4.11, but now have a new MacBook Pro but not newest fcp an
-
BPM process archiving "Processing of archiving write command failed"
Can someone help me with the following problem. After archiving a BPM proces, I get the following messages (summary): ERROR Processing of archiving write command failed ERROR Job "d5e2a9d9ea8111e081260000124596b3" could not be run as user"E61006".
-
Can I turn a tool recorded artwork into a video?
I want to show a video turning into a drawing. Can I use the tool recording feature to change my photo into a drawing and than export that to video?
-
ITunes Wi-Fi Please Help!
How do you actually get the iTunes button on your home screen? Its not there and I synced the latest version of software for my iPhone. Am I the only person having this problem?
-
Client call using XML over Http using HttpClient
Using HTTPClient while calling HTTPPost method to generate request for external system using XML over http using below code client.getState().setCredentials(new AuthScope(ipAddress,portNumber),new UsernamePasswordCredentials(username, password));