I know I'll feel like a tard when I figure this one out. I'm trying to do a very simple client/server and run it from the command line. It runs fine from Eclipse, but not from cmd. Here's the client:
package com.mycompany.pdr.client;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SimpleClientSend {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 11048;
String dataToSend = "HELLO SERVER";
System.out.println("> Trying to connect...");
System.out.println("> Opening connection to server [" + host + ":"
+ port + "]...");
Socket socket1Connection;
try {
socket1Connection = new Socket(host, port);
System.out.println("> Connected...");
System.out.println("> Trying to write data... [ " + dataToSend + " ]");
BufferedOutputStream bos = new BufferedOutputStream(
socket1Connection.getOutputStream());
/*
* Instantiate an OutputStreamWriter object with the optional
* character encoding. e.g. UTF-8
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
// Writing to server
osw.write(dataToSend);
osw.flush();
System.out.println("> Writing to server done...");
socket1Connection.close();
} catch (UnknownHostException e) {
System.out.println(e.getLocalizedMessage());
System.out.println("Unknown Host. Please check if the server is running at the IP & port");
//e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
System.out.println("Could not send data. Giving up.");
//e.printStackTrace();
}
System.out.println("> End of connection...");
}
}
My directory structure is : (MyWorkspace)/myProject/com/mycompany/pdr/client
I run javac SimpleClientSend.java from inside the client folder, and I get a class file, no errors. I run java SimpleClientSend and I get a NoClassDefFound message:
Exception in thread "main" java.lang.NoClassDefFoundError: SimpleClientSend (wrong name: com/iai/pdr/client/SimpleClientSend)
I've tried using -cp . when I run java to follow the suggestions of every other article out there(but what's the point if . is already in my classpath?), I've tried running it from outside the client folder, everything just gives me the same error. In eclipse, all I had to do was paste the java files into a blank project and it ran. What am I doing wrong here?
You need to specify the full name of your class (including package).
java com.mycompany.pdr.client.SimpleClientSend
It is important that the base of the structure for your class(es) is included in your class path. Normally . is included, so if you run the command above when your are in myProject it should work.
If you are in another folder you should add the myProject to your class path, such as:
java -cp ...MyWorkspace/myProject com.mycompany.pdr.client.SimpleClientSend
The ... of course is since I don't know your full path.
Related
I'm able to create docker container for ACE-TAO service , and able to access it from parent windows machine using port-forwarding concept.
From browser i try to hit the localhost:forward-port and getting "ERR_EMPTY_RESPONSE" and TAO service is running in docker container.
If I want to verify in local, whether its connected properly or not.
How can I write Java code to verify?
The following java code connects to localhost:17500 and prints out a message saying whether or not it could create a tcp connection.
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
try {
Socket clientSocket = new Socket("localhost", 17500);
System.out.println("Could connect");
}
catch (ConnectException e) {
System.out.println("Cannot connect");
}
}
}
I'm trying to create simple socket application using sockets to send stream from linux (64x ArchLinux) to server (Windows XP).
Code I'm using I found on the internet, just to check if it is working. What is interesting the code works perfectly if I'm using Windows XP (server) and Win 8 (client), but when client is on ArchLinux it does not work. Is there some special way to connect Windows-Linux ?
Server.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Server_pzm {
public static void main(String args[]) {
String data = "Toobie ornaught toobie";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("192.168.224.78", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
// while (!in.ready()) {} line removed
System.out.println(in.readLine());
System.out.print("'\n");
in.close();
}
/* lines removed catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
} */
// added exception handling
catch(UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
EDIT
Sorry, I did not specify what I meant by not working. I meant I got an exception which later prints System.out.print("Whoops! It didn't work!\n"); as in the catch blok. Win 8 and Arch Linux are installed on the same laptop, while the code is on my dropbox folder in both systems (so the code is the same) - I will post the actual exception, after I get back to my laptop
EDIT 2:
I updated code and this is exception I got:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
java.net.ConnectException: Connection refused
This has two possible meanings.
There is nothing listening at the address:port you tried to connect to.
There is a firewall rule in the way.
More likely 1. Firewalls usually just drop the packets, which causes a connection timeout rather than a refusal.
Are you sure you can establish connection between those systems? I have compiled and run your code on Windows 7 and Linux Mint on Virtualbox and it works correctly.
What do you mean "It doesn't work"? Does it throw any exception? If you just don't have any output, try to run it again and wait about 30 seconds.
For me it's just a network problem. So you should also try to ping your windows machine from linux and then try to telnet to server.
Edit:
So we know it is a network problem. First try to ping ip server from Linux system.
ping 192.168.224.78
If it didn't work, you should check if both machines are in the same subnet 192.168.224.0 assuming the mask is 255.255.255.0. You need just to type ifconfig in console.
In next step you should try to disable windows firewall. Here is an instruction how to do that.
On my machine, the following code compiles within Eclipse but throws an exception within Netbeans. The error message says "Exception in thread "main" java.net.BindException: Address already in use".
What is the proper configuration within Netbeans to make this code compile? It seems like the problem has to do with the fact that I have two main functions. If I start running either one of the apps, the second will fail to start, throwing the exception posted above.
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
InputStreamReader mySR = new InputStreamReader(SS_accept.getInputStream());
BufferedReader myBR = new BufferedReader(mySR);
String temp = myBR.readLine();
System.out.println(temp);
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Client myCli = new Client();
myCli.run();
}
public void run() throws Exception {
Socket mySkt = new Socket("localhost", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
myPS.println("Hello server");
}
}
The problem is due to the fact that you left one instance of your server running and then started another one.
The way to achieve what I want is to right-click on the particular class (ex. Server.java) that I want to run and select "Run this file". This enables me to run only the Server app. Then, do the same process for the other file, Client.java.
However, Netbeans is somewhat confusing/deceiving in this particular circumstance. What Netbeans does is it runs the Server process, but labels that process as the name of the project (ex. MyTestNetworkingProject) and puts a run number on it, thus giving us MyTestNetworkingProject run #1 (it actually leaves out the #1 on the first process). Then, if I go to the Client.java file and select "Run this file", it generates a second process, MyTestNetworkingProject run #2. It then generates a second results window down at the bottom of the screen, as it generates these in new tabs as new processes get created.
Because of the nature of my specific code, what I wanted to see in my results window to confirm that my application was working was I wanted to observe the Server.java results window (which in this case is MyTestNetworkingProject run #1). Given my exact sequence of steps outlined above of running the different files, run #2 is the last run process and thus the tab on top, covering the run #1 tab. I can click on run #1 and see the results I was hoping to see in the console ("Hello server"), but I just have to know/remember that MyTestNetworkingProject run #1 represents the Server app and not the Client app.
Uncool, IMO.
If you write this in Windows OS,you can use "netstat -nao" to see which process use the 9999 port.If it is some unimportant process,you can kill this process.Otherwise you can change the port of the pragram.
I change the port address and it work for me in the Neat Beans IDE . This problem will come if we used the same port address for other one times . so to fix this error you have to change the port address and I am sure it will work
Server.java
public class SocServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(5001);
Socket client = server.accept();
DataOutputStream os = new DataOutputStream(client.getOutputStream());
os.writeBytes("Hello Sockets\n");
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java
public class SocClient {
public static void main(String[] args) {
try {
Socket socClient = new Socket("localhost", 5001);
InputStream is = socClient.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String receivedData = br.readLine();
System.out.println("Received Data: " + receivedData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
refer above code and it works for me..
I did try the method catch and solved the problem.
I'm currently writing a jdbc client-server socket application in java. I've been having a bit of trouble initializing jdbc as i'm not using an ide, just a text editor and jdk. I have put my jdbc driver in my jdk and jre classpaths C:\Program Files\Java\jdk1.6.0_20\jre\lib\ext and \jre\lib\ext . I also renamed the jar to com.mysql.jdbc.driver , but I have still had no luck. Is this a problem with the driver not being found or is it something else?
Here is my error:
C:\Users\imallin\My Documents>java Provider
Waiting for connection
Connection received from 127.0.0.1
server>Hi welcome to the Cyfieithu Eadar-Theangachadh translation server, please
enter a command. Type cmd to see a list of commands
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Provider.insertData(Provider.java:82)
at Provider.run(Provider.java:40)
at Provider.main(Provider.java:118)
Here is my code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Provider{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Connection con;
Provider(){}
void run()
{
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Hi welcome to the Cyfieithu Eadar-Theangachadh translation server, please enter a command. Type cmd to see a list of commands");
//4. The two parts communicate via the input and output streams
do{
try{
insertData();
message = (String) in.readObject();
System.out.println("client>" + message);
if (message.equals("register"))
sendMessage("first name?");
String firstName = (message);
sendMessage("first name = " + firstName);
insertData();
if (message.equals("listlanguages"))
sendMessage("English \n Thai \n Geordia \n Gaelic \n Welsh \n Gaelic \n Urdu \n Polish \n Punjabi \n Cantonese \n Mandarin");
if (message.equals("bye"))
sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
private void insertData()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/translator","root","");
String sql = "Insert INTO users (ID, firstName) VALUES ('123','123')";
Statement statement = con.createStatement();
statement.execute(sql);
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}
}
Like other answers have hinted already, the jdbc Jar is not on your classpath.
To fix this, you need to declare, when running your Java main file, that it should use that Jar, by doing:
java -cp "nameOfJar.jar" Provider
This is assuming that your jar is on the same dir as your Provider file, if not you should specify the path to it.
It's totally optional, but I like having a directory named "lib" where I put all the jars I need to run my project, then you can add to classpath by doing:
java -cp "./lib/*;." NameOfJavaClassWithMain
Ultimately, you might end up having several directories or jars that you need to add to your classpath, you do this by using the ; (: in linux) separator, like:
java -cp "./lib/*;./conf/configurationFile.properties;." NameOfJavaClassWithMain
If your .class is not on one of the Jars, you might have to add the local directory to your classpath:
java -cp "./lib/*;." NameOfJavaClassWithMain
If you have a package declaration on your class (you should), you need to reference the class by that fully classified name (package+ClassName), like so:
java -cp "./lib/*;." my.package.NameOfJavaClassWithMain
Ultimately your classpath for jdbc is not set.
This is what I do ( a bad practice )
extract your jar file. (say you are working in home directory ~, and the name of directory where jar file is extracted is odbc)
then set your classpath to
export CLASSPATH=~/odbc:
( do not forget to add : after the path ;-) )
Oh could not realize that you are working on windows machine.
Then
set environment variable ( create if does not exists ) CLASSPATH to c:\odbcdir
or other-way is to use java -cp pathToJAR.jar Main.
The MySQL Driver jar is not on the classpath. You need to fix this, by using the -cp argument tojava.
i am trying to code a small XMPP gtalk client in java. I know there is a lot of libraries that help you that but the RFC is so easy to understand that i decide to write a client by myself.
I know that the gtalk server is talk.google.com:5222 but when i try this small program i get this result :
HTTP/1.1 302 Found
Location: http://www.google.com/talk/
Content-Type: text/html
Content-Length: 151
<HTML><HEAD><TITLE>302 Moved</TITLE></HEAD><BODY><H1>302 Moved</H1>The document has moved here.</BODY></HTML>
I also tried to connect the location specified but it doesn't work. Here is my code in java :
package fr.grosdim.myjabber;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
.getDefault();
try {
Socket s = new Socket("talk.google.com", 5222);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("<?xml version=\\'1.0\\' encoding=\\'utf-8\\' ?>");
out
.println("<stream:stream to='talk.google.com:5222' "
+ "xmlns='jabber:client'"
+ " xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
out.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(s
.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
out.println("</stream>");
s.close();
} catch (SSLPeerUnverifiedException e) {
System.out.println(" Erreur d'auth :" + e.getLocalizedMessage());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
}
How can i connect to the gtalk server?
XMPP isn't a trivial protocol to implement, and I don't think you'll get very far by sending hand-crafted XML strings to the server.
I'd recommend studying some existing source code.
Spark and OpenFire are one example of a nice open source XMPP client and server implementation in java.
You might try getting OpenFire running locally in a debugger (or with verbose logging turned on) so you can get an idea of what it's doing with your packets.
Although not directly related, you may need a server to test against and one for which you can see the source. I suggest that you look at what the Vysper guys are doing http://mina.apache.org/vysper/
You have several problems with your code, not counting the stylistic one of not using a DOM before sending (which is a best practice in the XMPP world).
You need to connect to "talk.l.google.com". See the results of "dig +short _xmpp-client._tcp.gmail.com SRV" on the command line to find out what servers to connect to.
In your XML prolog, you're double escaping the single quotes, which will actually send a backslash.
The to attribute in your stream:stream should be "gmail.com", without the port number.
All of that being said, I'll second the other posters with a plea for you to not start another Java client library, but to pitch in on an existing one.
Why are you writing an XML version before writing the stream stanza? The server is expecting a stream of defined format, and not an XML structure. Remove this line
"out.println("< ? xml version=\\'1.0\\' encoding=\\'utf-8\\' ?>")"
then it will work for sure.