Help with sockets and Blackberry - java

i'm trying to convert a simple irc client written on java to blackberry, it uses sockets, here it is:
package seinao;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
// The server to connect to and our details.
String server = "127.0.0.1";
String nick = "nickname";
String login = "nickname";
// The channel which the bot will join.
String channel = "#oi";
// Connect directly to the IRC server.
Socket socket = new Socket(server, 6667);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));
// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : Java IRC Hacks Bot\r\n");
writer.write("Hello World!");
writer.write("PRIVMSG " + channel + "Hello!\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.toLowerCase( ).startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else if(line.toLowerCase( ).contains("funciona")){
writer.write("PRIVMSG " + channel + " Olaz!\r\n");
writer.flush();
System.out.println("mermao ta foda");
}
else {
// Print the raw line received by the client.
System.out.println(line);
}
}
}
}
but i noticed there is no java.net.* on blackberry eclipse plugin soo, what should I do ? can someone help me ? what should I use for sockets ? I'm new to java and blackberry programming but i'm learning it quite fast, thanks alot

If I remember correctly, it's SocketConnection that you use. Search through the Blackberry API for what you'll need, it'll be way more helpful.

Related

451 4.5.0 SMTP protocol violation in basic java mail client

I have an assignment that requires me to build a very basic mail client to send an email on my school's server. If I open a command prompt on my computer and run telnet with these exact commands, the message goes through, but something in the program is causing it to kick back an error message. The exact response is:
451 4.5.0 SMTP protocol violation, see RFC 2821 e127si46647995qkb.26 - gsmtp
Here is the part of my code where I believe the issue to lie:
private void sendMessage(String from, String to, String subject, String msg) {
Socket socket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
socket = new Socket("ALT3.ASPMX.L.GOOGLE.COM", 25);
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
} catch (Exception e) {
System.out.println(e);
}
if (socket != null && os != null && is != null) {
try {
os.writeBytes("HELO\n");
os.writeBytes("MAIL From: <" + from + ">\n");
os.writeBytes("RCPT TO: <" + to + ">\n");
os.writeBytes("DATA\n");
os.writeBytes("From: <" + from + ">\n");
os.writeBytes(subject);
os.writeBytes(msg); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}

Multiplayer game in Java. Connect client (player) to game that was created by other client

I am working on multiplayer game and I cant to find out how can I connect other clients to the created game. I mean that client A create a socket connection to the server and how other clients (A,B...) can connect to the client A?
Can somebody help me please?
P.S. I'm new with network programming, so if you can attach some example i would be very grateful.
Another client cannot be connected to the Client A because of his firewall.
You can create two majors kinds of network:
Server-Client
Peer-to-Peer
But a client can save some data to the server and the server can send them to all the clients (you don't need a Peer-to-Peer network for allow the Client B to send some data to the Client A).
Example: The Client B send his map position to the server, the server send the data to all the clients, so the Client A is able to draw a character tileset at the position of the Client B.
For connect two PCs together, you need to forward a port from the modem of your server to the PC used as server, and open the port from the firewall of the PC used as server.
You can also take a look here Creating a Multiplayer game in python, I give an example where the clients was able to connect them together with IRC and play at a Tic-Tac-Toe game (so you didn't have to manage a server). I have add an example in Java at the end of this post.
A simple server example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket listener = new ServerSocket(4000);
String line;
try
{
while (true)
{
Socket socket = listener.accept();
BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
try
{
writerChannel.write(new Date().toString() + "\n\r");
writerChannel.flush();
while ((line = readerChannel.readLine()) != null)
{
System.out.println(line);
}
}
finally
{
socket.close();
}
}
}
finally
{
listener.close();
}
}
}
A simple client example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Date;
public class Client
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 4000);
BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
writerChannel.write(new Date().toString() + "\n\r");
writerChannel.flush();
while ((line = readerChannel.readLine()) != null)
{
System.out.println(line);
}
}
}
Also take a look at:
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Client
{
public static void main(String[] args) throws Exception
{
SSLSocketFactory socketBuilder = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) socketBuilder.createSocket("127.0.0.1", 4000);
}
}
A simple IRC example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Client
{
public static void main(String[] args) throws Exception
{
SSLSocketFactory socketBuilder = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket) socketBuilder.createSocket("irc.freenode.net", 6697);
BufferedWriter writerChannel = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader readerChannel = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line, computerName, nick, login, channel = "#bot", channelPassword = "";
long id = 1;
computerName = java.net.InetAddress.getLocalHost().getHostName();
nick = computerName + "_" + id;
login = computerName + "_" + id;
writerChannel.write("NICK " + nick + "\r\n"); // Join IRC with a specific Nick
writerChannel.write("USER " + login + " 8 * :" + login + " \r\n"); // Join IRC with a specific User
writerChannel.flush();
while ((line = readerChannel.readLine()) != null)
{
if (line.indexOf("004") != -1) // If connected
{
break;
}
else if (line.indexOf("433") != -1) // If Nick already in use
{
id++;
nick = computerName + "_" + id;
login = computerName + "_" + id;
writerChannel.write("NICK " + nick + "\r\n");
writerChannel.write("USER " + login + " 8 * :" + login + " \r\n");
writerChannel.flush();
}
}
writerChannel.write("JOIN " + channel + " " + channelPassword + "\r\n"); // Join a channel
writerChannel.flush();
while ((line = readerChannel.readLine()) != null)
{
try
{
line = line.substring(line.indexOf("#"));
channel = line.substring(0, line.indexOf(" "));
if (line.toLowerCase().startsWith("ping")) // avoid ping time-out
{
writerChannel.write("PONG :" + line.substring(5) + "\r\n");
writerChannel.flush();
}
else if (line.toLowerCase().contains("!ping"))
{
writerChannel.write("PRIVMSG " + channel + " :pong\r\n");
writerChannel.flush();
}
else if (line.toLowerCase().contains("!join"))
{
String newChannel = line.substring(line.indexOf("!join") + 6);
int stringPosition;
if ((stringPosition = newChannel.indexOf(" ")) != -1)
{
String newPassword = newChannel.substring(stringPosition + 1);
newChannel = newChannel.substring(0, stringPosition);
writerChannel.write("JOIN " + newChannel + " " + newPassword + "\r\n");
writerChannel.flush();
}
else
{
writerChannel.write("JOIN " + newChannel + "\r\n");
writerChannel.flush();
}
}
else if (line.toLowerCase().contains("!leave"))
{
writerChannel.write("PART " + channel + "\r\n");
writerChannel.flush();
}
else if (line.toLowerCase().contains("!quit"))
{
writerChannel.write("QUIT\r\n");
writerChannel.flush();
System.exit(0);
}
}
catch (Exception e)
{
}
}
}
}
I cannot give you an example for a Peer-to-Peer network because I have never do it. This is really difficult and you have to do a lot of research on internet.
More informations:
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
https://docs.oracle.com/javase/tutorial/networking/sockets/
http://www.oracle.com/technetwork/java/socket-140484.html
You need a multithreaded server for handle many different connections.
Hint - I have already answer at some similar questions. Even if the programming language are sometime different, I give you the link, the logic is always the same so it can maybe help you:
Creating a Multiplayer game in python
Xcode Mass Multiplayer (Not What You're Probably Thinking)
How would an MMO deal with calculating and sending packets for thousands of players every tick for a live action game?
Here is one way to handle it. When a player wants to create a game, his copy of the application should open a ServerSocket on a known port - a port number that the application knows - and maybe display to the player the IP address that the socket was opened on.
Then when another player wants to join a game, she should enter that same IP address and her copy of the application should connect using a regular client Socket, the IP address entered, and the known port that the application knows.
Check the Socket and ServerSocket javadoc for details.

How I can develop an "xdcc send" in Java?

I found this code to communicate with an IRC server (see below). However I did not find how to send a command to download or upload in xdcc.
Once connected to the IRC server and positioned in the channel. I want to send a command like.
/msg bot_name xdcc send #number_of_file
Thank you in advance for your answers, examples and help.
import java.io.*;
import java.net.*;
public class HackBot {
public static void main(String[] args) throws Exception {
// The server to connect to and our details.
String server = "irc.freenode.net";
String nick = "simple_bot";
String login = "simple_bot";
// The channel which the bot will join.
String channel = "#irchacks";
// Connect directly to the IRC server.
Socket socket = new Socket(server, 6667);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));
// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : Java IRC Hacks Bot\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.toUpperCase( ).startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else {
// Print the raw line received by the bot.
System.out.println(line);
}
}
}
}
Your code shows only the minimum requirements needed to open a connection to a IRC server and keep it connected, actually the entire IRC protocol is much more complex and it is not implemented in the code.
The xdcc send is simply a normal IRC message sent privately to a specific other user (usually a bot) of the IRC server, therefore you can send it by using the command PRIVMSG:
writer.write("PRIVMSG " + botNickName + " :xdcc send #" + numberOfPack + "\r\n");
where botNickName and numberOfPack are two String variables containing the nickname of the bot (i.e. the recepient of the message) and the number (in string format) of the package in which you are interested.
Nevertheless you must consider that the DCC is an entire completely different protocol from the IRC protocol itself: it uses the CTCP message on IRC:
DCC SEND <filename> <ip> <port>
only to start a DCC session, but then there is the DCC protocol in order to manage the communication client-to-client. So if you really want to make the DCC works you should also implement it, but it would not be a quick job.

Java socket server, PHP socket client; communication works, however PHP 'echoes' data only after the socket connection is closed

I am trying to create a simple socket based server/client communication between a Java-based socket server and PHP-based socket client. I am getting all the responses as expected but not immediately. Here is what I am trying to do. PHP client sends a command to the Java server, it responds back with an answer. This answer should be displayed on PHP page immediately. Then a second command is sent and again, the server sends a response which should be displayed immediately. However in my case, the responses are 'echoed' only after entire socket based communication is terminated. That is after I close the socket connection from PHP client.
Following is my Java Socket Server code:
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(final Socket csocket) {
this.csocket = csocket;
}
private static void download(final String url) {
try {
final URL downloadURL = new URL(url);
URLConnection conn = null;
try {
conn = downloadURL.openConnection();
final InputStream inputStream = conn.getInputStream();
final long filesize = conn.getContentLength();
System.out.println("Size of file : " + (filesize / 1024)
+ " (kb)");
final FileOutputStream outputStream = new FileOutputStream(
System.getProperty("user.dir") + "/test.exe");
final long startTime = System.currentTimeMillis();
final byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
final long endTime = System.currentTimeMillis();
System.out.println("File downloaded");
System.out.println("Download time in sec. is : "
+ ((endTime - startTime) / 1000));
outputStream.close();
inputStream.close();
} catch (final IOException e) {
e.printStackTrace();
}
} catch (final MalformedURLException e) {
e.printStackTrace();
}
}
public static void main(final String args[]) throws Exception {
final ServerSocket ssock = new ServerSocket(3333);
System.out.println("Listening on " + ssock.toString());
while (true) {
final Socket sock = ssock.accept();
System.out.println("Connected to " + sock.getRemoteSocketAddress());
new Thread(new MultiThreadServer(sock)).start();
}
}
#Override
public void run() {
try {
final BufferedReader br = new BufferedReader(new InputStreamReader(
this.csocket.getInputStream()));
final BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(this.csocket.getOutputStream()));
bw.write(this.csocket.getRemoteSocketAddress().toString()
.replace("/", "")
+ "\n");
bw.flush();
String line;
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("getMacName")) {
final String macName = InetAddress.getLocalHost()
.getHostName();
bw.write(macName + "\n");
bw.flush();
System.out.println("Machine Name : " + macName);
} else if (line.equalsIgnoreCase("getMacIP")) {
final String macIP = InetAddress.getLocalHost()
.getHostAddress();
bw.write(macIP + "\n");
bw.flush();
System.out.println("Machine IP : " + macIP);
} else if (line.equalsIgnoreCase("getCurrentVersion")) {
final String currVersion = "0.1a";
bw.write(currVersion + "\n");
bw.flush();
System.out.println("Current Version : " + currVersion);
} else if (line
.equalsIgnoreCase("downUrl:http://webserver/webapp/test.exe")) {
final String url = line.substring(8);
bw.write("Downloading : " + url + "\n");
bw.flush();
MultiThreadServer.download(url);
System.out.println("URL : " + url);
} else if (line.equalsIgnoreCase("exit")) {
bw.write("Closing\n");
bw.flush();
bw.close();
br.close();
System.out.println("Exiting!");
this.csocket.close();
break;
}
}
} catch (final IOException e) {
e.printStackTrace();
}
}
}
Following is my sample PHP client source code:
<html>
<head>
<title>Socket Connection Test</title>
</head>
<body>
<h3>Testing Socket Connection</h3>
<br>
<?php
$host="127.0.0.1";
$port = 3333;
$fp;
$macName;
$macIP;
$message;
$result;
// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
{
$result = "Error: Could not open socket connection! Error No: " . $errno . ". Error String: " . $errstr;
die($result);
}
else
{
$message = fgets ($fp, 1024);
$message = trim($message);
echo "Connected to remote server on current port : " . $message;
echo "<br>";
sleep(5);
// get machine name
fwrite ($fp, "getMacName\n");
$macName = fgets ($fp, 1024);
$macName = trim($macName);
echo "Machine Name : " . $macName;
echo "<br>";
sleep(5);
// get IP address
fwrite ($fp, "getMacIP\n");
$macIP = fgets ($fp, 1024);
$macIP = trim($macIP);
echo "Machine IP : " . $macIP;
echo "<br>";
sleep(5);
fwrite ($fp, "getCurrentVersion\n");
$currVersion = fgets ($fp, 1024);
$currVersion = trim($currVersion);
echo "Current Version : " . $currVersion;
echo "<br>";
sleep(5);
fwrite ($fp, "downUrl:http://webserver/webapp/text.exe\n");
$downResponse = fgets ($fp, 1024);
$downResponse = trim($downResponse);
echo "Download Response : " . $downResponse;
echo "<br>";
sleep(5);
fwrite ($fp, "exit\n");
$exitStatus = fgets ($fp, 1024);
fclose ($fp);
echo "Connection Closed.";
}
?>
</body>
</html>
In this case, the entire PHP output is displayed at the end. I even tried putting sleeps at various places, however it seems to be waiting for socket connection to be closed before writing the output. How can I can I get the output "LIVE". Like a normal chat communication? What am I doing wrong here?
Your script works okay, and has no big flaws for what you're looking for. Since you obtain the desired result when you run the script from command line rather than a web browser, we can pinpoint the cause of the issue: the HTTP protocol
HTTP isn't made for sustained connections (like you're used to with Java sockets) but it's simplified workflow is based along the lines of Request/Elaborate/Response/Forget. Therefore, you can't have a "live chat" with a pure HTML/PHP over HTTP solution.
Alas, not all your hopes are lost! To implement a "live" communication you can use Ajax, which isn't too hard to get used to. I've said "live" because it's still an HTTP based solution, but at least you can have requests and receive responses from within the same webpage, which is the closest you can get with the HTML/PHP/AJAX triad.
It seems you dont understand php with http well .
You will get the HTML response only after your php client code completes execution. (i.e) all your echo's will be put in place where you specified and returned as a whole.
Putting sleep will only delay the execution.

java.lang.NumberFormatException: null in Integer.parseInt

Okay, the following are 2 classes that I am using in creating a simple TFTP (Trivial File Transfer Protocol) program. I am running a server instance and a client instance of this program. What I am trying to accomplish is this:
The client connects to the server and sends a message of a specific file that it wants. The server locates the file and sends a response (either a 1 or 0... 1 meaning the file is there, and 0 meaning that it is not). Then the server will send the content of the file to the client application. The files I am trying to send are just simple text files.
Right now, I am able to receive the name of the text file that the client wants, but then when I go to send back the response, I am not getting anything returned. Also below are the methods that the server and the client both run.
This is the server instance
SwingUtilities.invokeLater(new Runnable(){
public void run(){
String fileRequest = UDPReceiver(SERVER_PORT_NUMBER);
outputArea.append("\n" + "File Requested: " + fileRequest + "\n");
outputArea.append("Determining if file exists...\n");
String checkFile = SHARED_DIR + "\\" + fileRequest;
outputArea.append("Checking location: " + checkFile + "\n");
boolean check = fileCheck(checkFile);
if(check == true){
outputArea.append("File location verified..." + "\n");
outputArea.append("Initiating transfer...." + "\n\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1");
}
else{
outputArea.append("File does not exist..." + "\n");
outputArea.append("Exiting run..." + "\n");
}
}
});
The client instance.
SwingUtilities.invokeLater(new Runnable(){
public void run(){
UDPSender(SERVER_HOSTNAME, SERVER_PORT_NUMBER, FILE_REQUEST);
String message = UDPReceiver(CLIENT_PORT_NUMBER);
outputArea.append("\n\n" + message + "\n");
if(message == "1"){
// File exists
outputArea.append("\n");
outputArea.append("File verified..." + "\n");
outputArea.append("Transfer initiated..." + "\n");
}
else{
// File doesn't exist
outputArea.append("\n");
outputArea.append("File does not exist..." + "\n");
outputArea.append("Terminating connection...");
}
}
});
Here are the Sender and Receiver methods.
private void UDPSender(String hostname, String port, String message){
DatagramSocket socket = null;
try{
// Create a datagram socket, look for the first available port
socket = new DatagramSocket();
outputArea.append("Using local port: " + socket.getLocalPort() + "\n");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PrintStream pOut = new PrintStream(bOut);
pOut.print(message);
// Convert printstream to byte array
byte[] bArray = bOut.toByteArray();
// Create a DatagramPacket, containing a maximum buffer of 256 bytes
DatagramPacket packet = new DatagramPacket(bArray, bArray.length);
outputArea.append("Looking for hostname " + hostname + "\n");
// Get the InetAddress object
InetAddress remote_addr = InetAddress.getByName(hostname);
// Check its IP Number
outputArea.append("Hostname has IP Address = " + remote_addr.getHostAddress() + "\n");
// Configure the DatagramPacket
packet.setAddress(remote_addr);
packet.setPort(Integer.parseInt(port));
// Send the packet
socket.send(packet);
outputArea.append("Packet sent at: " + new Date() + "\n");
// Display packet information
outputArea.append("Sent by: " + remote_addr.getHostAddress() + "\n");
outputArea.append("Sent from: " + packet.getPort() + "\n");
socket.close();
}
catch(UnknownHostException ue){
outputArea.append("Unknown host: " + hostname + "\n");
outputArea.append("Unknown host: " + ue + "\n");
}
catch(IOException e){
outputArea.append("Error: " + e + "\n");
}
}
private String UDPReceiver(String portNum){
String message = "";
DatagramSocket socket = null;
try{
// Create a DatagramSocket
socket = new DatagramSocket(Integer.parseInt(portNum));
outputArea.append("Listening on local port " + socket.getLocalPort() + "\n");
// Create a DatagramPacket, containing a maximum buffer of 256 bytes
DatagramPacket packet = new DatagramPacket(new byte[256], 256);
// Receive a packet - remember by default this is a blocking operation
socket.receive(packet);
outputArea.append("Packet received at " + new Date() + "\n");
// Display packet information
InetAddress remote_addr = packet.getAddress();
outputArea.append("Sender: " + remote_addr.getHostAddress() + "\n");
outputArea.append("From Port: " + packet.getPort() + "\n");
CLIENT_HOSTNAME = remote_addr.getHostAddress();
//CLIENT_PORT_NUMBER = Integer.toString(packet.getPort());
// Display packet contents, by reading from byte array
ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData());
// Display only up to the length of the original UDP packet
for(int i = 0; i < packet.getLength(); i++){
int data = bin.read();
if(data == -1){
break;
}
else{
message = message + (char)data;
//outputArea.append(Character.toString((char)data));
}
}
socket.close();
return message;
}
catch(IOException e){
outputArea.append("Error: " + e + "\n");
message = "Error: " + e;
return message;
}
}
Any help that you folks can offer would be greatly appreciated. The main thing I am trying to figure out is how to be able to get the server and client to be able to send messages back and forth. Thanks in advance guys.
EDIT:
I am also getting an error now in Netbeans when I run this project. I think it has something to do with this line of code in the UDPReceiver method:
socket = new DatagramSocket(Integer.parseInt(portNum));
But I can't figure out what is wrong with that.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at tftp_gui.main.UDPReceiver(main.java:508)
at tftp_gui.main.access$800(main.java:20)
at tftp_gui.main$10.run(main.java:374)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
you approach is wrong, as it is requires opened client port, anyway your particular problem is because you're not sending back result when file is not found:
check:
if(check == true){
outputArea.append("File location verified..." + "\n");
outputArea.append("Initiating transfer...." + "\n\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1");
}
else {
outputArea.append("File does not exist..." + "\n");
outputArea.append("Exiting run..." + "\n");
UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "0"); // here you should send 0
}
also, you have small problem here: if(message == "1") it should look like if ("1".equals(message))
Your error is self explainable - you're haven't declared proper CLIENT_PORT_NUMBER or SERVER_PORT_NUMBER, here is what I've used for testing:
private final static String SERVER_PORT_NUMBER = "1234";
private static String CLIENT_HOSTNAME;
private static final String CLIENT_PORT_NUMBER = "2345";
private static final String FILE_REQUEST = "a.txt";
private static final String SHARED_DIR = "d:/";
private static final String SERVER_HOSTNAME = "localhost";

Categories