Sending classes in the net..?
well i got to the part of my project where i need to build a client and server for my project.
but i realized that i have too many parameters to send to/from the server and string just doesnt cut it.
so i decided that i need to send objects from classes that i made.
but i dont know how can i send this trough the net
Google for serialization. It does exactly what you want.
Similar Messages
-
Which class in the net.scarlet.tsith package should I use?
I'll Tumble 4 Ya
Church of the Poison Mind
Karma Chameleon
or
TimeI would suggest methods from a related, but undocumented Class from the same package - DeadOrAlive.brandNewLover or DeadOrAlive.youSpinMeRound - similar functionality, but much more interesting.
Good Luck
Lee -
I cannot reveive mail,but can send and I'm connected to the net.
http://support.apple.com/kb/HT1277
This should help you sort things out. -
I am running Mac OS 10.6.7 I cannot run a java based program from the net when parental controls are set the error is The error is Load: class installer.CheckVersion 13. class not found
Then, talk to the person running the lab.
-
Why cant i send this to the cost class on button click?
when the calculate button is clicked i want the program to check and see if a certain checkbox is selected and if set a variable in another class.
in the code below. why does it not recognize that i am trying to send the variable from the checkbox to the set method in the cost class?
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==jbnCalculate)
String f = jtfFirst.getText();
String l = jtfLast.getText();
String id = jtfID.getText();
if(cbCream.isSelected()){
app1.setCream(ch);
package final_Kelm;
public class GMCCost extends GMCEmployee {
double white;
double wheat ;
double creamCheese;
double butter;
double peachJelly;
double blueberryJam;
//double regularCoffee = 1.25;
//double mocha = 2.75;
//double latte = 3.05;
double coffee;
double total, subTotal;
double TAX_RATE = 0.0825;
public GMCCost()
total = 0.0;
subTotal = 0.0;
public void setCoffee(double c)
if(c==1)
coffee = 1.25;
else if(c==2)
coffee = 2.75;
else if(c==3)
coffee = 3.05;
else
coffee = 0.0;
public double getCoffee()
return coffee;
public void setCream(double ch)
ch = 0.5;
ch = creamCheese;
public double getCream()
return creamCheese;
}i am having the same trouble with the coffee. i cannot add it to the output by "Coffee Price: " + app1.getCoffee() + . . . . .why is this considered wrong or bad . . .
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==jbnCalculate)
double butter, peach, blueberry, white, wheat;
double creamCheese, subTotal, total;
String f = jtfFirst.getText();
String l = jtfLast.getText();
String id = jtfID.getText();
double TAX_RATE = 0.0825;
if(cbCream.isSelected()){
creamCheese = 0.5;
else{
creamCheese = 0.0;
if(cbButter.isSelected()){
butter = 0.25;
else {
butter = 0.0;
if(cbPeach.isSelected()) {
peach = 0.75;
else {
peach = 0.0;
if(cbBlueberry.isSelected()) {
blueberry = 0.75;
else {
blueberry = 0.0;
if(jrbWhite.isSelected()) {
white = 1.25;
else{
white = 0.0;
if(jrbWheat.isSelected()) {
wheat = 1.50;
else {
wheat = 0.0;
double coffee = jcbCoffee.getSelectedIndex();
if(coffee==0) {
coffee = 0.0;
else if(coffee==1) {
coffee = 1.25;
else if(coffee==2) {
coffee = 2.75;
else {
coffee = 3.05;
subTotal = white + wheat + creamCheese + butter + peach + blueberry + coffee;
total = subTotal + (subTotal * TAX_RATE);
jtaOutput.setText("");
output = output+ "Employee Information: " +"\nStaff ID: " + id + "\nStaff First Name: " + f + "\nStaff Last Name: " + l +
"\nInvoice: " + "\nSubtotal: " + subTotal + "\nTotal: " + total;
jtaOutput.append(output);
}as compared to the code i first posted . . . . . this code works . . . the gui works . . . and im assuming this class of code can run all by itself and does have or need anything to do with the other 3 classes are in this program (see previous thread).
this program works but all the code is in the button handler class . . . i do not need to send anything anywhere, i do not need to use set get methods . . . so why would this code be frowned upon? -
How do I establish a connection to another Java program on the net?
Hi all,
I have been reading the java tutorial to find a solution to my problem but I havent really found what Im looking for.
I want to establish a connection that allows a client to get a copy of an object from a running java-application on a server on the internet.
I have read about the Socket-class but the tutoral advices only to use it on a locale network. I know IDL and RMI only by name - is this what I should be reading about?
If one of you guys have a source-code example on how to make java programs communicate over the net, please post it!
Regards AlbertAssuming this is "wide area" stuff, not just on a local area network, your best bet is to stick to http connections. You need a web server, probably Tomcat.
Your client can connect using URL.openConnection().
As to protocols you could use SOAP. It has the advantage that you can get the code for it for free, but it can be pretty complicated to configure. In particular it only knows how to transmit a limited set of object types and if you want to go beyond them you have to write converters. SOAP servers typically run under an web server anyway. SOAP converts all the data to XML for transmission.
However it may be simpler to use Java's built in serialisation facility and send your data as an ObjectStream.
In the set up you're talking about the message going to the server seems a lot simpler than the response. It may make sense to send your data as normal keyword parameters of a POST transaction but to have the server respond with an Object stream. That's well within the normal operation of a web server. -
Object can't be send over to the server.
Hi to everyone,
I'm doing a connection between client and server. The client will send image from the platform to the server. The server will then create an folder in the server-side to store the images.
Thank you for reading. Hope to hear from you soon. Anytime you need clarifation, you could ask. I'll be more willingly to feel you in in more details.
IMclient.java -- file
import java.awt.geom.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
// ========================== START OF IMAGECLIENT ===========================
public class IMclient extends JFrame implements ActionListener,ChangeListener
private JMenuBar mainMenu;
private JMenuItem open, save, exit, scale;
private JMenu fileMenu, editMenu;
private JPanel mainPane, butPane;
private JFileChooser imagesFile;
private JButton butSend;
private JLabel imageLabel; //A display area for a short text string or an image, or both
JPanel imagePanel;
JLabel imgPanel = new JLabel();
BufferedImage buffImage=null;
BufferedImage bimage;
ImageStorage dImage=null;
// JSlider variable
final int MIN = 0;
final int MAX = 255;
final int INIT = MAX/2;
JSlider redSlider, greenSlider, blueSlider;
// BufferedImage bimage;
int r,g,b;
int w,h;
int pixels[];
Image img;
String fname= "babymin05.gif";
// Declare all the Input/Output object variables.
Socket toHost = null;
//PrintWriter out = null;
ObjectInputStream in = null;
ObjectOutputStream objectOut = null;
Container cpane;
// ================================ Constructor ===============================
public IMclient(String host, int port){
initGUI();
initSocket(host, port);
dImage = new ImageStorage(fname);
updateImage();
public void updateImage()
buffImage = dImage.getImage(); //return buffered image
// img = (Image)bimage; //cast buffered image as images
displayImage(buffImage); //display the images
//added from rgbslider
//JSlider RedSlider,BlueSlider,GreenSlider;
public void displayImage(BufferedImage buffImage)
//to create and display an image
//BufferedImage bimage = rgb.getColor();
ImageIcon icon = new ImageIcon(buffImage);
System.out.println(icon);
imgPanel.setIcon(icon);//to set image visible
imgPanel.repaint();
public void stateChanged(ChangeEvent e)
//return buffered image from ImageStorage class.
bimage = getColor();
// displayImage(bimage);
public BufferedImage getColor()
//to get the array of pixels of the buffered image
pixels = new int[dImage.getWidth()*dImage.getHeight()];
//return the pixels value of bufferedImage
pixels = dImage.getPixelsArray();
int [] rgb = new int[3];
int pix=0;
for (int i=0 ; i<pixels.length ; i++)
//to get the r,g,b value from the array
rgb = dImage.getRGB(pixels);
r = redSlider.getValue();
g = greenSlider.getValue();
b = blueSlider.getValue();
//to set the pixels to the final value
pixels = dImage.setRGB(r,g,b);
dImage.setPixels(pixels);
//to set the pixels array value and the RGB value
dImage.setImage(pixels);
bimage = dImage.getImage();
//to return the buffered image
return bimage;
public JPanel sliderGUI()
JPanel slidePanel = new JPanel();
slidePanel.setLayout(new GridLayout(3,2));
setSlider();
JLabel redLabel = new JLabel("Red");
JLabel blueLabel = new JLabel("Blue");
JLabel greenLabel = new JLabel("Green");
slidePanel.add(redLabel);
slidePanel.add(redSlider);
slidePanel.add(blueLabel);
slidePanel.add(blueSlider);
slidePanel.add(greenLabel);
slidePanel.add(greenSlider);
return slidePanel;
// setSlider() consists of the three silders (r,g and b).
private void setSlider(){
blueSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
blueSlider.setMajorTickSpacing(MAX);
blueSlider.setMinorTickSpacing(MIN);
blueSlider.setPaintLabels(true);
redSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
redSlider.setMajorTickSpacing(MAX);
redSlider.setMinorTickSpacing(MIN);
redSlider.setPaintLabels(true);
greenSlider = new JSlider(JSlider.HORIZONTAL, MIN, MAX, INIT);
greenSlider.setMajorTickSpacing(MAX);
greenSlider.setMinorTickSpacing(MIN);
greenSlider.setPaintLabels(true);
blueSlider.addChangeListener(this);
redSlider.addChangeListener(this);
greenSlider.addChangeListener(this);
public BufferedImage getBufferedImage()
return bimage;
// ================================ initGUI() =================================
public void initGUI()
cpane = getContentPane();
cpane.setBackground(Color.white);
cpane.setLayout(null);
//to set the close menu on the menubar
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//Open the menu in order to img from any folder
imagesFile = new JFileChooser();
imagesFile.addActionListener(this);
//create an intermedia panel to hold panel and button
mainMenu = new JMenuBar();
setJMenuBar(mainMenu);
setContentPane(cpane);
fileMenu = new JMenu("File");
mainMenu.add(fileMenu);
editMenu = new JMenu("Features");
mainMenu.add(editMenu);
/* == JMenuItem(open, save, exit) to be added into the JMenu(fileMenu) == */
open = new JMenuItem("Open...");
save = new JMenuItem("Save...");
exit = new JMenuItem("Exit...");
scale = new JMenuItem("Scale");
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(exit);
editMenu.add(scale);
/* =================== End of adding JMenuItem() ======================== */
//add events to the JMenuItem(open, save, exit)
open.addActionListener(this);
save.addActionListener(this);
exit.addActionListener(this);
scale.addActionListener(this);
/* =============== Create a button =======================*/
butSend = new JButton("Send");
butSend.addActionListener(this);
JPanel butPane = new JPanel();
butPane.setLayout(new BorderLayout());
butPane.add(butSend);
/* =============== End Create button =======================*/
/* =============== Create a Image Panel =======================*/
imgPanel = new JLabel();
imagePanel= new JPanel(new BorderLayout());
//imgPanel.setBorder(BorderFactory.createRaisedBevelBorder());
imagePanel.setBorder(BorderFactory.createRaisedBevelBorder());
//imageLabel = new JLabel();
imagePanel.add(imgPanel);
/* =============== End of Image Panel =======================*/
// creates a new Panel
JPanel rgb=sliderGUI();
cpane.add(rgb);
cpane.add(imagePanel);
cpane.add(butPane);
Insets insets = cpane.getInsets();
imagePanel.setBounds(50 + insets.left, 20 + insets.top, 300, 236);
butPane.setBounds(400 + insets.left, 220 + insets.top, 90, 40);
rgb.setBounds(50 + insets.left, 300 + insets.top, 400, 250);
//to set the size of the frame
setSize(1024,768);
//to set the main pane visible to the user
setVisible(true);
// =========================== actionPerformed() ==============================
public void actionPerformed(ActionEvent e)
if(e.getSource()==(open))
imagesFile.showOpenDialog(this); //to have the OPEN dialog box
if(e.getSource() == imagesFile)
//to get the file from the exact folder that the user clicks on
fname = imagesFile.getSelectedFile().getAbsolutePath();
updateImage();
if(e.getSource() == (exit))
System.exit(0); //exit the program
if(e.getSource() == butSend)
sendImage(img);
/* ========================== initSocket ================================
* Set up the socket connection to the server.
* 1: connect to the server at <host>, <port>.
* 2: getOutputStream() will return an output stream for our socket (ie
the stream is FROM the client TO the server. Since we want to send
Image objects to the server, we need to create a stream which can
send object, ie. an ObjectInputStream.
3: getInputStream will return an input stream for our socket (ie. stream
is FROM the server TO the client. We use this to create a stream that
can transmit formatted characters.
protected void initSocket(String host, int port)
try{
toHost = new Socket(host, port); //1
//always do OUT then do IN
objectOut = new ObjectOutputStream(toHost.getOutputStream()); //2
in = new ObjectInputStream(toHost.getInputStream()); //3
sendObject(bimage);//here got problem ba
Object input = null;
try{
while((input = in.readObject()) != null) //test whether object is null
Image img = (Image)input;
sendImage(img);
}catch (Exception e){}
toHost.close();
catch (UnknownHostException e)
System.err.println("Unknown host in initSocket()");
catch (IOException e)
System.err.println("IO error in initSocket()");
/* =========================== sendObject() ==============================
* objectOut is the ObjectOutputStream. To send an object across the stream,
* use the writeObject() method of ObjectOutputStream. The flush() method
* ensures that data is sent.
protected void sendObject(Object obj)
try{
objectOut.writeObject(obj);
objectOut.flush();
}catch(IOException e){
System.out.println("Sending failed");
System.exit(1);
/* =========================== sendImage() ==============================
* sendImage() creates the requested Image Object, then calls sendObject() to
* send the image's width, height, and raw data to the server. The server uses
* these to reconstruct the image, we could use the ImageIO class to read the
* image file.
* The getImage() method return immediately, even if the image data has been
* fully loaded. Once the data is locked, the width and height, values using the
* getWIdth() and getHeight() methods.
protected void sendImage(Image img)
int w,h;
//get the image from the imagePanel and return the buffered image
img = dImage.getImage();
while ((w = img.getWidth(null)) == -1){}
//System.out.println("Width of image: "+ w);
while ((h = img.getHeight(null)) == -1){}
int[] buffer = new int[w * h];
/* The PixelGrabber class implements an ImageConsumer which can be
* attached to an Image or ImageProducer object to retrieve a subset
* of the pixels in that image.
PixelGrabber px = new PixelGrabber (img,0,0,w,h,buffer,0,w);
try{
px.grabPixels();
}catch (InterruptedException ie){
System.err.println("Pixels grab failed");
sendObject(new Integer(w));
sendObject(new Integer(h));
sendObject(buffer); //buffer contains all the bytes for the image
public static void main(String [] args)
if(args.length != 2)
System.err.println("Requirement Paramenters: <host>,<port number>");
System.exit(0);
String host = args[0];
int port = Integer.parseInt(args[1]);
IMclient is = new IMclient(host,port);
IMserver.java-- file
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class IMserver
Image images;
public IMserver()
try
start();
}catch (IOException ioe){
System.err.println("Start Failed:"+ioe);
private void start() throws IOException
ServerSocket ss = new ServerSocket(22222);
while(true)
new ImageServerConnection(ss.accept(), images).start();
public static void main(String[] args)
IMserver im = new IMserver();
class ImageServerConnection extends Thread
//Declare the Input/Output object variable
Socket clientSocket = null;
ObjectOutputStream objectOut = null;
ObjectInputStream inObject = null;
Image img;
/* ====================== ImageServerConnection ================================
*ImageSeverConnection is a subclass of Thread. ImageServerConnection handles a
* connection with a client. It has methods for initialzing a connection and for
* receieving objects to clients.
public ImageServerConnection(Socket client, Image img)
clientSocket = client;
this.img = img;
/* ========================= run() ===========================
* run() is overrriden from Thread. In this case, we call the
* newSocket method to initialize the socket and perform initial
* tasks.
public void run()
try{
newSocket();
}catch(IOException ioe){
System.err.println("Socket failed: " + ioe);
/* ========================= newSocket() ===========================
* This is where we do all the client connection work
private void newSocket() throws IOException
inObject = new ObjectInputStream(clientSocket.getInputStream());
//objectOut = new ObjectOutputStream(clientSocket.getOutputStream());
getImage();
clientSocket.close();
/* =============================== getImage() =================================
* getImage() assumes that a connection already exists to the server.
* First, getImage transmits the image we want to get.
* Then, we wait to read the 3 objects sent by the server's ObjectOutputStream:
-- an Integer object, representing the width of the image
-- an Imteger object, representing the height of the image
-- an Image object
* The first two are Integer objects, NOT primitive int types. This
* is because the ObjectOutputStream can only transmit objects, not primitive
* types (to transmit primitive types, use a DataOutputStream).
* 1: Read the three objects sent by the server. Note each object must be cast to
its appropriate type, since readObject() returns an Object. To get the value
of an Integer object, we use its intValue() method, which returns the primitve
int value of the Integer.
* 2: The buffer object is an array of integers, which represents the image
data. In other words, buffer is an array of integers in memory which is
the source of the raw image data. Java has a special MemoryImageSource
class which is used to construct Images from raw data in memory. So, in
step 3, we create a MemoryImageSource object using the width, height, and
buffer objects.
* 3: We want to create an Image object using the MemoryImageSource object we
created in step 3. To do this, we use the createImage() method of the
Component class. Since this client class extends Frame, and Frame is a
subclass of Component, we can call createImage() directly.
* 4: Once the Image is created, it will be passed into the folder for storage
private void getImage()
Component c=null;
try{
objectOut.writeObject(img);
objectOut.flush();
int w = ((Integer)inObject.readObject()).intValue();
int h = ((Integer)inObject.readObject()).intValue();//1
int [] buffer = (int[])inObject.readObject(); //2
Image img = c.createImage(new MemoryImageSource(w, h, buffer, 0, w)); //3
//create an new folder to store those sent images
File f = new File ("C:\\Sweet_Memory");
//you can also check whether such folder exists or not.
if (!f.exists ()){
f.mkdir ();
//how to store image into the file????
}catch(Exception e){
System.out.println("Server-side: "+ img);
System.err.println("Receiving failed: "+ e);
}The codes below have error message showing "IO error in initSocket() " which is in the initSocket method and "Sending failed" which is in sendObject method. HOwever i can't figure out why this error message is shown. Can anyone kindly help me out? Did i declare the wrong thing?
Please clarify with me if i'm not clear, thank a lot. Any help will be appreaciated.
IMclient.java
public class IMclient extends JFrame implements ActionListener,ChangeListener
// Declare all the Input/Output object variables.
Socket toHost = null;
ObjectInputStream in = null;
ObjectOutputStream objectOut = null;
public void actionPerformed(ActionEvent e)
if(e.getSource() == butSend)
sendImage(img);
protected void initSocket(String host, int port)
try{
toHost = new Socket(host, port); //1
//always do OUT then do IN
objectOut = new ObjectOutputStream(toHost.getOutputStream()); //2
in = new ObjectInputStream(toHost.getInputStream()); //3
sendObject(bimage);
Object input = null;
try{
while((input = in.readObject()) != null) //test whether object is null
Image img = (Image)input;
sendImage(img);
}catch (Exception e){}
toHost.close();
catch (UnknownHostException e)
System.err.println("Unknown host in initSocket()");
catch (IOException e)
System.err.println("IO error in initSocket()");
protected void sendObject(Object obj)
try{
objectOut.writeObject(obj);
objectOut.flush();
}catch(IOException e){
System.out.println("Sending failed");
System.exit(1);
protected void sendImage(Image img)
int w,h;
//get the image from the imagePanel and return the buffered image
img = dImage.getImage();
while ((w = img.getWidth(null)) == -1){}
while ((h = img.getHeight(null)) == -1){}
int[] buffer = new int[w * h];
PixelGrabber px = new PixelGrabber (img,0,0,w,h,buffer,0,w);
try{
px.grabPixels();
}catch (InterruptedException ie){
System.err.println("Pixels grab failed");
sendObject(new Integer(w));
sendObject(new Integer(h));
sendObject(buffer); //buffer contains all the bytes for the image
public static void main(String [] args)
if(args.length != 2)
System.err.println("Requirement Paramenters: <host>,<port number>");
System.exit(0);
String host = args[0];
int port = Integer.parseInt(args[1]);
IMclient is = new IMclient(host,port);
IMserver.java
public class IMserver
Image images;
public IMserver()
try
start();
}catch (IOException ioe){
System.err.println("Start Failed:"+ioe);
private void start() throws IOException
ServerSocket ss = new ServerSocket(22222);
while(true)
new ImageServerConnection(ss.accept(), images).start();
public static void main(String[] args)
IMserver im = new IMserver();
class ImageServerConnection extends Thread
//Declare the Input/Output object variable
Socket clientSocket = null;
ObjectOutputStream objectOut = null;
ObjectInputStream inObject = null;
Image img;
public ImageServerConnection(Socket client, Image img)
clientSocket = client;
this.img = img;
public void run()
try{
newSocket();
}catch(IOException ioe){
System.err.println("Socket failed: " + ioe);
private void newSocket() throws IOException
inObject = new ObjectInputStream(clientSocket.getInputStream());
getImage();
clientSocket.close();
private void getImage()
Component c=null;
try{
objectOut.writeObject(img);
objectOut.flush();
int w = ((Integer)inObject.readObject()).intValue();
int h = ((Integer)inObject.readObject()).intValue();//1
int [] buffer = (int[])inObject.readObject(); //2
Image img = c.createImage(new MemoryImageSource(w, h, buffer, 0, w)); //3
}catch(Exception e){
System.err.println("Receiving failed: "+ e);
} -
Once I send 1 string, the rest are cut off, any ideas?
Hello everyone.
For some reason when I send my first string through the socket, everything works fine. But after that Its cutting off the first 2 or 3 characters of the string and I have no idea why because I'm flushing the output buffer before and after I send the the string to the output buffer.
note: complete code can be found here:
http://cpp.sourceforge.net/?show=38132
Am I not flushing right?
Here's the code:
public class MultiThreadServer implements Runnable {
//csocket is whatever client is connecting to this server, in this case it will
//be a telnet client sending strings to the server.
Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
public void run() {
//setting up sockets
Socket outputServ = null;
//create a message database to store events
MessageDB testDB = new MessageDB();
try {
//setting up channel to recieve events from the omnibus server
BufferedReader in= new BufferedReader(
new InputStreamReader(
csocket.getInputStream()));
PrintWriter out2
= new PrintWriter(
new OutputStreamWriter(
csocket.getOutputStream()));
//This socket will be used to communicate with the z/OS reciever
//we will need a new socket each time because this is a multi-threaded
//server thus, the z/OS reciever (outputServ) will need to be
//multi threaded to handle all the output.
outputServ = new Socket("localhost",1234);
if(outputServ.getLocalSocketAddress() == null)
System.out.println("OutputServer isn't running...");
//Setting up channel to send data to outputserv
PrintWriter out
= new PrintWriter(
new OutputStreamWriter(
outputServ.getOutputStream()));
String input;
//accepting events from omnibus server and storing them
//in a string for later processing.
while ((input = in.readLine()) != null)
//looking to see what telnet gets
out2.println(input);
out2.flush();
//accepting and printing out events from omnibus server
//also printing out connected client information
System.out.flush();
System.out.println("Event from: " + csocket.getInetAddress().getHostName()
+"-> "+ input +"\n");
System.out.flush();
//sending events to output server
out.flush();
out.println(input);
out.flush();
//close the connection if the client drops
if(in.read() == -1)
System.out.println("Connection closed by client.");
break;
//cleaning up
in.close();
out.close();
outputServ.close();
csocket.close();
catch (SocketException e )
System.err.println ("Socket error: " + e);
catch(UnknownHostException e)
System.out.println("Unknown host: " + e);
catch (IOException e)
System.out.println("IOException: " + e);
}Here's some example output I'm getting from the telnet screen which is (out2) stream:
This is a test
This is another test
his is another test
This is yet another test
his is yet another test
This is a test worked fine, as you can see, it outputed This is a test when I typed it in.
The next string "This is another test" fails, as you can see its echoing out:
his is another test
I'm also printing out the contents to the console, and i'm getting out the same thing:
Enter port to run server on:
3333
Listening on : ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=3333]
Waiting for client connection...
Socket[addr=/127.0.0.1,port=2184,localport=3333] connected.
hostname: localhost
Ip address: 127.0.0.1:3333
Event from: localhost-> This is a test
Event from: localhost-> his is another test
Event from: localhost-> his is yet another test
Connection closed by client.
ANy help would be great!
Message was edited by:
lokieI posted more compact code so its easier to see and understand: The run() function is where the problem is occurring.
//SAMPLE OUTPUT FROM CONSOLE
Enter port to run server on:
3333
Listening on : ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=3333]
Waiting for client connection...
Socket[addr=/127.0.0.1,port=2750,localport=3333] connected.
hostname: localhost
Ip address: 127.0.0.1:3333
Event from: localhost-> This is a test
Event from: localhost-> his is a test
Event from: localhost-> his is a test
Connection closed by client.
//------END OF SAMPLE OUTPUT-----//
//---THis class is called everytime a new thread is created,
//only 1 thread is created because only 1 client is connecting to the
//server
package server;
//parser server
import java.io.IOException.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
public void run() {
try {
//setting up channel to recieve events from the omnibus server
BufferedReader in= new BufferedReader(new InputStreamReader(csocket.getInputStream()));
String input;
//accepting events from omnibus server and storing them
//in a string for later processing.
while ((input = in.readLine()) != null)
//accepting and printing out events from omnibus server
//also printing out connected client information
System.out.println("Event from: " + csocket.getInetAddress().getHostName()
+"-> "+ input +"\n");
System.out.flush();
//close the connection if the client drops
if(in.read() == -1)
System.out.println("Connection closed by client.");
break;
//cleaning up
in.close();
csocket.close();
catch (SocketException e )
System.err.println ("Socket error: " + e);
catch(UnknownHostException e)
System.out.println("Unknown host: " + e);
catch (IOException e)
System.out.println("IOException: " + e);
//This is the main function, the only thing it does is
//create a new thread on each connection.
package server;
//This is the parser Client that will parse messages and send to the
//z/Os output Server
import java.io.*;
import java.net.*;
public class MainTest
public static void main(String args[]) throws Exception
//get console input
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter port to run server on: ");
String input = stdin.readLine();
int servPort = Integer.parseInt(input);
//setting up sockets
ServerSocket ssock = null;
Socket sock = null;
try
//setting up server to run on servPort
ssock = new ServerSocket(servPort);
System.out.println("Listening on : " + ssock);
System.out.println("Waiting for client connection...");
while (true) {
//waiting for client to connect to server socket
sock = ssock.accept();
System.out.println(sock + " connected.");
//get host information
InetAddress clientIa = sock.getInetAddress( );
String clientName = clientIa.getHostName();
String clientIp = clientIa.getHostAddress();
int localPort = sock.getLocalPort();
System.out.println("hostname: "+clientName +
'\n' + "Ip address: " + clientIp
+":"+ localPort + "\n\n");
new Thread(new MultiThreadServer(sock)).start();
catch (SocketException e )
System.out.println ("Socket error: " + e);
catch(UnknownHostException e)
System.out.println("Unknown host: " + e);
catch (IOException e)
System.out.println("IOException: " + e);
} -
How can i send mail to the yahoo mail or gmail or something else
hello guys,
i want to know how to send mails to the yahoo or gmail or something else.i heard that we have to change some smtp address and some port number. can any body suggest me to get that.please help me
any replies will be appreciated greatly.Hi chnaresh,
This is the code I use to send mail, it's not specific to gmail, but it works. The "props" object expects the usual mail properties, "mail.smtp.host", "mail.user" or "mail.smtp.user", as well as "mail.smtp.ssl" which you'd want to set to "true" if you're using gmail. It also expects "mail.smtp.passwd" or "mail.passwd" which my gut tells me is unsafe, but I'm not sure why.
Good luck,
radikal_3dward
public static int sendMail(final Properties props, String subject, String body, String to, String cc, String bcc, String from, File[] attachments, boolean toStdOut)
throws javax.mail.internet.AddressException, javax.mail.MessagingException, javax.mail.NoSuchProviderException
Session sess;
//props.setProperty("mail.debug", "true");
if(props.getProperty("mail.smtp.ssl") != null && props.getProperty("mail.smtp.ssl").equalsIgnoreCase("true"))
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
String portStr = ((props.getProperty("mail.smtp.port") != null) ? (props.getProperty("mail.smtp.port")) : "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", portStr);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
sess = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
String userName = ((props.getProperty("mail.smtp.user") != null) ? props.getProperty("mail.smtp.user") : props.getProperty("mail.user"));
String passwd = ((props.getProperty("mail.smtp.passwd") != null) ? props.getProperty("mail.smtp.passwd") : props.getProperty("mail.passwd"));
if(userName == null || passwd == null)
return null;
return new PasswordAuthentication(userName , passwd);
else
String portStr = ((props.getProperty("mail.smtp.port") != null) ? (props.getProperty("mail.smtp.port")) : "25");
sess = Session.getInstance(props, null);
//sess.setDebug(true);
MimeMessage mess = new MimeMessage(sess);
mess.setSubject(subject);
StringTokenizer toST = new StringTokenizer(to, ",;");
while(toST.hasMoreTokens())
Address addr = new InternetAddress(toST.nextToken());
mess.addRecipient(Message.RecipientType.TO, addr);
if(from != null)
StringTokenizer fromST = new StringTokenizer(from, ",;");
InternetAddress[] fromAddrs = new InternetAddress[fromST.countTokens()];
for(int i = 0; fromST.hasMoreTokens(); i++)
fromAddrs[i] = new InternetAddress(fromST.nextToken());
mess.addFrom(fromAddrs);
if(cc != null)
StringTokenizer ccST = new StringTokenizer(cc, ",;");
while(ccST.hasMoreTokens())
Address addr = new InternetAddress(ccST.nextToken());
mess.addRecipient(Message.RecipientType.CC, addr);
if(bcc != null)
StringTokenizer bccST = new StringTokenizer(bcc, ",;");
while(bccST.hasMoreTokens())
Address addr = new InternetAddress(bccST.nextToken());
mess.addRecipient(Message.RecipientType.BCC, addr);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
if(body != null)
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
if(attachments != null)
for(int i = 0; i < attachments.length; i++)
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachments);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachments[i].getName());
multipart.addBodyPart(messageBodyPart);
mess.setContent(multipart);
Address[] allRecips = mess.getAllRecipients();
if(toStdOut)
System.out.println("done.");
//System.out.println("Sending message (\"" + mess.getSubject().substring(0,10) + "...\") to :");
System.out.println("Sending message (\"" + mess.getSubject() + "...\") to :");
for(int i = 0; i < allRecips.length; i++)
System.out.print(allRecips[i] + ";");
System.out.println("...");
Transport.send(mess);
if(toStdOut)
System.out.println("done.");
return 0; -
I need to send email from the database.
Two ways that I am familiar with -
1. using VB/ODBC controls;
2. dbms_pipe
Anyone knows a more 'direct' solution?
Regards
Anatoliy Smirnov
nullby the way how can u send attchments with mails from database.
chetan
try this...(thanks for the subject line help)
the first message line will be read by non MIME compliant readers, the second message line with be in the body of the note, the nest 2 (third and fourth) will come in as attachments ( text ). Change the Content-type for things like word docs or other 8bit docs (Content-type: application/msword) and write_raw_data for the 8Bit parts
CREATE OR REPLACE PROCEDURE send_mail_test (sender IN VARCHAR2,
recipient IN VARCHAR2, subject IN VARCHAR2,
message IN VARCHAR2)
IS
mailhost VARCHAR2(30) := 'smtp.naxs.net';
mail_conn utl_smtp.connection;
cv_cCRLF VARCHAR2(10) := UTL_TCP.CRLF;
lv_message varchar2(4000);
BEGIN
mail_conn := utl_smtp.open_connection(mailhost, 25);
utl_smtp.helo(mail_conn, mailhost);
utl_smtp.mail(mail_conn, sender);
utl_smtp.rcpt(mail_conn, recipient);
utl_smtp.open_data(mail_conn);
utl_smtp.write_data(mail_conn,'From: ' | | sender | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'To: ' | | recipient | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'Subject:' | | subject | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'MIME-Version: 1.0' | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'Content-Type: multipart/mixed; ');
utl_smtp.write_data(mail_conn,'boundary="NextPart_000_01C002D3.EB460626"' | | cv_cCRLF);
utl_smtp.write_data(mail_conn, cv_cCRLF | | message| |' first mess part'| | cv_cCRLF);
utl_smtp.write_data(mail_conn,'--NextPart_000_01C002D3.EB460626' | | cv_cCRLF);
utl_smtp.write_data(mail_conn, cv_cCRLF | | message| | ' second mess part'| | cv_cCRLF);
utl_smtp.write_data(mail_conn,'--NextPart_000_01C002D3.EB460626' | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'Content-Type: text/plain; charset=us-ascii'| | cv_cCRLF);
utl_smtp.write_data(mail_conn, cv_cCRLF | | message| | ' third mess part'| |cv_cCRLF);
utl_smtp.write_data(mail_conn,'--NextPart_000_01C002D3.EB460626' | | cv_cCRLF);
utl_smtp.write_data(mail_conn,'Content-Type: text/plain; charset=us-ascii'| | cv_cCRLF);
utl_smtp.write_data(mail_conn, cv_cCRLF | | message| | ' fourth mess part'| |cv_cCRLF);
utl_smtp.write_data(mail_conn,'--NextPart_000_01C002D3.EB460626--' | | cv_cCRLF);
utl_smtp.close_data(mail_conn);
-- utl_smtp.data(mail_conn, message);
utl_smtp.quit(mail_conn);
EXCEPTION
WHEN OTHERS
THEN
DECLARE
error_code NUMBER := SQLCODE;
error_msg VARCHAR2(2000) := SQLERRM;
error_info VARCHAR2(30);
BEGIN
DBMS_OUTPUT.PUT_LINE('We have an error: '| |error_code| |' '| |error_msg);
END;
END;
show errors;
null -
Cannot Send Messages Using the Server
I am dependent (during the day) on a wireless connection to the Minneapolis Wi-Fi system (U.S. Wireless).
I've got an e-mail account with comcast and I have successfully interfaced this with the Apple Mail application that came with OS X 10.5.4 and for many weeks have been happily sending and receiving e-mails. But....
I've been on the road and had to connect with Hotel internet services and I was picking up free WiFi in NYC when I was there.
I first noticed the problem when I was staying at a hotel in Vermont.
I would try to send e-mails and I would get the message:
CANNOT SEND MESSGE USING THE SERVER __________.
Select a different outgoing mail server....
Now, I am back home and using my U.S. Wireless connection (which has been really bad lately).
I keep getting these blasted messages and my mail sometimes goes through but more than often, I get these "cannot send message.." notices and my e-mail just sits there going nowhere in the outbox.
How can I solve this problem?Beside the SMTP name -- smtp.comcast.net -- there is a pair of arrows, with one pointing up and one pointing down. If you click on those arrows you will be presented with a list of all SMTP ever enter (you may only have one), and also the command to Edit Server List. If you choose Edit Server List, you will be presented with a completely new setup window, dealing only with SMTP servers, and that window will have two tabs, one of which is also Advanced.
From the name, smtp.comcast.net, without your Username appended, would indicate that an Authentication of None is currently in effect. With changes that Comcast has made recently, whether you use Port 25 or Port 587, I believe you would have to use Password Authentication, most certainly if the latter Port 587 is chosen.
If you click on the link below, although not for Comcast, you will nevertheless see in section 12 through 15, screenshots that cover the SMTP setup that I am describing above.
http://wildblueworld.com/dishmail.net/howdoi-applemail.php#2
Ernie -
OSX Mail - Cannot send message using the server ....
Hi there,
Mac Pro with OSX 10.6.
*Can receive mail, but can no longer send email* using the program Mail.
Been getting the popup "Cannot send message using the server [shawmail.vc.shawcable.net] for the past 3 days. I hadn't changed anything about my computer, and have had the Mac for 2+ years. So this just started doing it on it's own.
I had a technical support guy from my service provider even interface with my computer, where he could see my desktop right over the internet, and he couldn't get it fixed either.
I googled this problem, and found solutions like:
1. Uncheck "Use SSL" (Done that, and it was never checked "on" to begin with)
2. Make sure Authentication is set to none, with no password (done that, and it wasn't set with a password to begin with)
3. Delete [user]/Library/Preferences/com.apple.mail.plist (done that, didn't do anything)
4. We even totally deleted my account, and started a new fresh one. Didn't work
The tech support guy did show me a way to email online, using the same email account. That worked, but it's a hassle to go onto a web-based email program -- it's not my preference. So, with great certainty, it's not my service provider, because I was able to send emails on this web-based email program using my email account.
So there, I'm stumped.
Hopefully someone can help. What's bizarre is that googling this problem, I have found many other people that say it happens arbitrarily, out of nowhere.I can't believe how ridiculous this issue is. i have been searching for days for a solution to this. i have tried EVERY recommendation on these forums and nothing works. It appears that this issue dates back to TIGER. I had this problem back in January and just bagged figuring it had something to do with iweb. I bought a new html program and was able to send out my newsletter last month no problem. Suddenly, one month later- here i am again, unable to send out my newsletter with no help from Apple or verizon, or these forims, or anyone else. To think that a company that I have stood behind and loved so much can't be be bothered fixing such a simple issue that has been going on now through 5 OS's (I am using Lion but I had the issue using leopard as well) is a disgrace.
-
Whoops! That's annoy the wife! (She can no longer surf the net)
I gave her my old eMac to organize her music and photos. I wasn't supposed to touch it. (She's had too many of my "computer fixes" that didn't quite work.) Since she only downloads songs about once a month, my brilliant plan to save money was to just unplug her computer's internet cable and plug that into my Airport base station. It seemed a good idea but the last time I tried plugging her computer back into the cable modem, her computer can't surf the net. Somehow, I seem to have messed her computer up without actually touching it. (Not that that will make a bit of difference to her.)
Please send any and all brilliant ideas on how I can fix this. That will be much appreciated.
Thanks.
Brian
800Mhz eMac. Superdrive. 60Gig HD Mac OS X (10.4.8)It sounds like you're not performing a complete power recycle each time you change the device connected to the cable modem.
Modem/Router Power ReCycling
- Power-off the Cable modem, AirPort Express Base Station (AX), & computer(s). (Wait at least 30 minutes. If possible, leave the modem off overnight.)
- Power-on the Cable modem; Wait at least 30 minutes.
- Power-on the AX; Wait at least 5 minutes.
- Power-on the computer(s) -
First i know that when i make any changes to the class library project i need to rebuild the project then to remove the Capture.dll from the TestScreenshot project and then to add again the updated Capture.dll
The problem for example in this case i'm trying to use a public static variable i add in the DXHookD3D9.
In the DXHookD3D9 i added this public static variable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using SlimDX.Direct3D9;
using EasyHook;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Drawing;
using Capture.Interface;
using SharpDX.Direct3D9;
namespace Capture.Hook
internal class DXHookD3D9: BaseDXHook
public DXHookD3D9(CaptureInterface ssInterface)
: base(ssInterface)
LocalHook Direct3DDevice_EndSceneHook = null;
LocalHook Direct3DDevice_ResetHook = null;
LocalHook Direct3DDevice_PresentHook = null;
LocalHook Direct3DDeviceEx_PresentExHook = null;
object _lockRenderTarget = new object();
Surface _renderTarget;
public static decimal framesperhourtodisplay = 0;
protected override string HookName
get
return "DXHookD3D9";
List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>(
framesperhourtodisplay
The problem is i can't even get to the Capture.Hook namespace and not to the DXHookD3D9 from the TestScreenshot application window project.
This is a screenshot:
For example fro the FramesPerSecond class i can use it get to it from the windows forms application.
namespace Capture.Hook
/// <summary>
/// Used to determine the FPS
/// </summary>
public class FramesPerSecond
int _frames = 0;
int _lastTickCount = 0;
float _lastFrameRate = 0;
Since it's public i guess.
But if i will change the DXHookD3D9 class from internal to public:
public class DXHookD3D9: BaseDXHook
I will get error on the DXHookD3D9:
Error 1
Inconsistent accessibility: base class 'Capture.Hook.BaseDXHook' is less accessible than class 'Capture.Hook.DXHookD3D9'
And the BaseDXHook class:
namespace Capture.Hook
internal abstract class BaseDXHook: IDXHook
protected readonly ClientCaptureInterfaceEventProxy InterfaceEventProxy = new ClientCaptureInterfaceEventProxy();
public BaseDXHook(CaptureInterface ssInterface)
this.Interface = ssInterface;
this.Timer = new Stopwatch();
this.Timer.Start();
this.FPS = new FramesPerSecond();
Interface.ScreenshotRequested += InterfaceEventProxy.ScreenshotRequestedProxyHandler;
Interface.DisplayText += InterfaceEventProxy.DisplayTextProxyHandler;
InterfaceEventProxy.ScreenshotRequested += new ScreenshotRequestedEvent(InterfaceEventProxy_ScreenshotRequested);
InterfaceEventProxy.DisplayText += new DisplayTextEvent(InterfaceEventProxy_DisplayText);
~BaseDXHook()
Dispose(false);
How can i solve it so i can use the variable framesperhourtodisplay in the DXHookD3D9 class with the TestScreenshot windows forms application ?Hi,
I dont know if it will work here, since I dont know the complete structure, but the base call must be public, if the derived class is public, so the base class is at least as accessible as the derived class.
Try make the base class public. (And maybe the base-class IDXHook of the base also...)
Or use a different approach and make only the properties public that are needed to be public by adding an extra class...
A structure could look like:(you need to create a class thats public in your dll and expose a property, and set this property in the internal class...)
In the Accessing class (here Form1)
public partial class Form1 : Form
public Form1()
InitializeComponent();
private void Form1_Load(object sender, EventArgs e)
C c = new C();
MessageBox.Show(B.F.ToString());
and in the class Lib:
internal class A
public A()
B.F = DateTime.Now.Millisecond;
public class B
public static int F { get; set; }
public class C
public C()
A a = new A();
(add a referenc to the class lib from the accessing project)
Regards,
Thorsten -
''locking this thread as duplicate, please continue at [https://support.mozilla.org/en-US/questions/1020334 /questions/1020334]''
In the blink of an eye, both Thunderbird and Firefox have BOTH STOPPED connecting to the Net. let me share with you what I have done... and what has been unsuccessful this far.
System & Software Pertinents..
Windows 7 x64 System running a i7 Intel CPU, with 8 GB of RAM and a 500 GB Drive.
Thunderbird is Version 24.2
Firefox is Version 27.
Here are the specific things that I have done, POST problem, to try and solve..
A) Check firewall settings... BOTH programs are cleared for Bit Passage
B) Check Anti-Virus.... Anti-Virus Disabled.. UNINSTALLED and Registry Cleaned.. still has the problem persisting..
C) Deleted and Reinstalled Thunderbird & Firefox Working Directories (without deleting User Profiles)... Problem still persisting..
D) Created NEW Profile with Profile Mgr in Firefox.. no go...
E) RAN WHOLE System VIRAL/MALWARE Check... .. No infections..
F) FRESH REINSTALLS of Thunderbird and Firefox... NO go...
G) Checked Processes using ENUM and DNS Checks... both check out fine!
H) OTHER browsers connect... OPERA.. Chrome and IE even... Also, Sea Monkey... but not Firefox.
In TRYING to create an e.mail account, Thunderbird's Account Creation interface sits there attempting to connect... no connection achieved...
Any help that you can offer is appreciated!!
Thank you all, in advance!Message to Toad-Hall
Thank you, for that. To be sure, I tried your suggestion, and selected "System Proxy" as the choice, for Thunderbird and Firefox. Rebooted, and looked at the outcome.. NO Joy.. :-(
I believe that I shall send the output of the Error Log in my next post. Perhaps someone can point me in the right direction after looking at the Error.log.
Thank you...Toad Hall. If you think of something else to try, I am ALL ears.. I shall keep trying..
Maybe you are looking for
-
My external hard drive is in Read Only mode...
My external hard drive, which I have used before, is in "Read Only Mode." I have put files on this drive and taken files off of it before, so it isn't an NTFS issue. I am still able to write with a different Mac. FYI, this is a Late-2011 Macbook Air.
-
How do i import bootcamp from a external hard drive
Hello, I have a 2007 24 inch 2.8ghz 7.1 intel imac, I have just upgraded my internal hard drive from a 500gb seagate barracuda to a 1.5tb western digital caviar green. I have a external usb 3.0 sata hard drive enclosure that has the original 500gb ha
-
ITunes no longer plays downloading movies!?!?
Okay so on the last two movie files I've downloaded from the iTunes store, I've had to wait for them to completely download before they will play at all. It used to be that I could play the movie as far as it was already downloaded. Now, when I click
-
I had a problem with my 4s battery so i took it to an apple store and they replaced the phone. However they had me backup my photos in icloud because i was goingto lose them otherwise. So now my question is how do i get my photos back?
-
Report RFIDESM340 - Substitute declaration
Hello, I have a problem with my tax report 340, for Spain, I need to make a correction on the previous declaration because we have realized that there is an error on. In RFIDESM340 program there is an option called "Substitute declaration" We have e