First, i am sorry maybe the title is wrong. I will explain my problem. I have one joptionpane with showinputdialog component to input server address. I want after click Cancel button, it will return to main window. But in my case, it instead to second joptionpane.
My English is bad :) ...
Anyone can help me ?
This is my code
private static int setPortNumber()
{
String portNumber = JOptionPane.showInputDialog(frame,
"Enter the Port number for server creation","Server Connection\n",
JOptionPane.OK_CANCEL_OPTION);
int PORT = Integer.parseInt(portNumber);
return PORT;
}
private static String setServerName()
{
server_address = JOptionPane.showInputDialog(frame,
"Enter Server Address or PC-Name.", "Server Connection",
JOptionPane.OK_CANCEL_OPTION);
return server_address;
}
private void networking() {
server_address = setServerName();
try {
PORT = setPortNumber();
if (server_address != null) {
sock = new Socket(InetAddress.getByName(server_address) ,
PORT);
}
else {
SocketException sc = new SocketException();
throw sc;
}
// Recieving input and output streams
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
br = new BufferedReader(ir);
pw = new PrintWriter(sock.getOutputStream());
login.setEnabled(true);
incoming.append("Connected to Server.please login.\n");
connect.setEnabled(false);
pw.println("~##~");
pw.flush();
login.requestFocus();
}
private void networking() {
server_address = setServerName();
if(server_address == null || server_address.equals("")){
//Handle what happens when the server name is empty (or the user clicked the cancel button. If you let the execution continue, then the try/catch block below will pop up the second jInputDialog
}
try {
PORT = setPortNumber();
if (server_address != null) {
sock = new Socket(InetAddress.getByName(server_address) ,
PORT);
}
else {
SocketException sc = new SocketException();
throw sc;
}
...
}
Run this example. It works fine
import javax.swing.JOptionPane;
public class NetWorking {
public static String server_address;
public static void main(String[] args) {
networking();
}
private static int setPortNumber()
{
String portNumber = JOptionPane.showInputDialog(null,
"Enter the Port number for server creation","Server Connection\n",
JOptionPane.OK_CANCEL_OPTION);
int PORT = Integer.parseInt(portNumber);
return PORT;
}
private static void setServerName()
{
server_address = JOptionPane.showInputDialog(null,
"Enter Server Address or PC-Name.", "Server Connection",
JOptionPane.OK_CANCEL_OPTION);
}
private static void networking(){
setServerName();
if (server_address == null) {
return;
}
Integer port = setPortNumber();
if (port != null) {
System.out.println(port);
}
}
}
Related
I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer
I write my own Java FTP server. Until recently I used PUttY to debug my control telnet connection and everything seemed fine - I had successful two-way communication. Now I try to debug my server with FileZilla, but it does not seem to read my text, nor to send some to server, so it just hangs and wait for something.
Control connection class
public class ControlConnection extends Thread {
private enum OperationMode {
ACTIVE, PASSIVE
}
private final Map<String, Supplier<String>> COMMANDS;
private String[] userTokens;
private User user;
private String userLogin;
private boolean authenticated;
private boolean dataConnected;
private boolean userExists;
private final Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private DataConnection ftpSession;
private OperationMode operationMode;
private String errorMessage;
public ControlConnection(Socket socket) {
super(ControlConnection.class.toString());
this.socket = socket;
// constants initialization
authenticated = false;
dataConnected = false;
// commands initialization
COMMANDS = new HashMap<>();
// commands init
}
#Override
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
sendGreetings();
IOProcessing.writeBytes(outputStream, pasvCommand());;
boolean running = true;
while (running) {
sendGreetings();
String input = IOProcessing.readBytes(inputStream);
if (!(input.equals("")))
System.out.println(input);
if (!checkInput(input))
continue;
userTokens = input.split(" ");
String command = userTokens[0].toUpperCase();
String answer = COMMANDS.get(command).get();
outputStream.writeBytes(answer);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
private boolean commonCheck() {
// some checks
return true;
}
private String getErrorMessage() {
return errorMessage;
}
public void sendGreetings() {
String greetings = String.format("220 Control connection established: %s", getConnectionInfo());
IOProcessing.writeBytes(outputStream, greetings);
}
public String getConnectionInfo() {
String info = String.format("%s: %d %s",
socket.getInetAddress().toString(), socket.getPort(), user != null ? user.getUsername(): "");
return info;
}
// input/output proccessing functions
public boolean checkInput(String input) {
// checks
return true;
}
// commands functions
private String pasvCommand() {
if (operationMode == OperationMode.PASSIVE) {
errorMessage = "Already in passive mode.%n";
return errorMessage;
}
String answer;
new ListenToSocket().start();
answer = String.format("227 Entering Passive Mode (%s, %d)",
"127.0.0.1", DataConnection.PORT);
operationMode = OperationMode.PASSIVE;
return answer;
}
private class ListenToSocket extends Thread {
public ListenToSocket() {
}
#Override
public void run() {
try {
ServerSocket ftpSocket =
new ServerSocket(DataConnection.PORT);
ftpSession =
DataConnection.getDataConnection(ftpSocket.accept());
if (ftpSession != null) {
ftpSession.start();
dataConnected = true;
String greetings = "Data connection established: " + ftpSession.getConnectionInfo();
IOProcessing.writeBytes(outputStream, greetings);
} else {
dataConnected = false;
}
} catch (IOException e) {
System.out.print(e);
}
}
}
also, server does not get user credentials, entered in FileZilla - input from server is always empty
IOProcessing class
public class IOProcessing {
private static final Charset UTF8_CHARSET;
static {
UTF8_CHARSET = Charset.forName("UTF-8");
}
public static String readBytes(DataInputStream inputStream) {
String result = "";
try {
int len = inputStream.available();
if (len == 0) {
return result;
}
byte[] byteInput = new byte[len];
inputStream.readFully(byteInput, 0, len);
result = new String(byteInput, "UTF-8").trim();
} catch (IOException e) {
System.err.println(e);
}
return result;
}
output FileZlla log
Status: Resolving address of localhost
Status: Connecting to [::1]:21...
Status: Connection established, waiting for welcome message.
You didn't show us the writeBytes. So I can only guess that you are not sending \r\n after the messages sent to the client. Particularly after the welcome message. So FileZilla keeps waiting forever for it, as any FTP client would do.
I have 3 classes (Client, Server, and Protocol) that allow a user to login and send a message to another user. I'm trying to add a password feature to the program but nothing I've tried has worked so far. I've added my code below, I want to prompt the user to put the password in after the error checking on the username has been done. The password should be compared and checked that it is a match, and only then should the user be able to view their messages and send messages.
Any tips would really be appreciated, thanks!
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String messages = "";
// Makes sure there are only two arguments entered
if(args.length != 2) {
System.err.println("Usage: java Client <host name> <port number>");
System.exit(1);
}
// Stores the command line arguments for readability further in the program
String host = args[0];
int port = Integer.parseInt(args[1]);
try (
// Creates the socket to be used
Socket s = new Socket(host, port);
// Reader and Writer to talk with Server
PrintWriter pw =
new PrintWriter(s.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(s.getInputStream()));
) {
// Reader to read from standard input (keyboard)
BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
// User interface
while (true) {
System.out.println("Please enter your username: ");
String username = keyboard.readLine();
// Check that the login is valid
if (username == null) {
System.out.println("No username entered");
}
else if (username.contains(" ")) {
System.out.println("Username cannot contain spaces");
}
// Send username to server and return number of messages
else {
pw.println(username);
messages = bf.readLine();
System.out.println("You have " + Integer.parseInt(messages) + " messages");
break;
}
}
// Enable the user to continue reading and composing messages until
// they choose to exit
while (true) {
System.out.println("Would you like to READ, COMPOSE or EXIT?");
String choice = keyboard.readLine();
// Shows the messages left for the user
if (choice.equals("READ")) {
pw.println("READ");
messages = bf.readLine();
if (messages == "0") {
System.out.println("NO MESSAGES");
}
else {
String incoming = bf.readLine();
System.out.println(incoming);
incoming = bf.readLine();
System.out.println(incoming);
}
}
// Allows user to write a message to another user
else if (choice.equals("COMPOSE")) {
pw.println("COMPOSE");
System.out.println("Enter message recipient");
String recipient = keyboard.readLine();
if (recipient == null) {
System.out.println("No recipient username entered");
}
else if (recipient.contains(" ")) {
System.out.println("Recipient username cannot contain spaces");
}
else {
pw.println(recipient);
System.out.println("Enter message to be sent");
String im = keyboard.readLine();
pw.println(im);
System.out.println(bf.readLine());
}
}
else if (choice.equals("EXIT")) {
pw.println("EXIT");
System.exit(1);
}
else {
System.out.println("Error: you must either READ, COMPOSE or EXIT");
}
}
}
// Catches the exception in which the server cannot be found
catch(IOException e) {
System.out.println("Error, could not connect to Server");
System.exit(1);
}
}
}
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
String request;
// Makes sure that the user has specified the correct number of command line arguments
if(args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
try (
// Creates a server socket and waits for a connection
ServerSocket ss = new ServerSocket(port);
// A socket to communicate with the client
Socket cs = ss.accept();
// Reader and Writer to talk with Client
PrintWriter pw =
new PrintWriter(cs.getOutputStream(), true);
BufferedReader bf = new BufferedReader(
new InputStreamReader(cs.getInputStream()));
)
// Links the server to the protocol
{
Protocol protocol = new Protocol();
protocol.storeUsername(bf.readLine());
pw.println(protocol.messagesNumber());
// Loop through user input until EXIT is entered
while (true) {
request = bf.readLine();
// Controls output if user inputs READ
if (request.equals("READ")) {
pw.println(protocol.messagesNumber());
pw.println(protocol.readSender());
pw.println(protocol.readMessage());
}
// Controls input if user inputs COMPOSE
else if (request.equals("COMPOSE")) {
String sender = bf.readLine();
String message = bf.readLine();
if (protocol.append(sender, message)) {
pw.println("MESSAGE SENT");
}
else {
pw.println("MESSAGE FAILED");
}
}
// Exits the server
else {
System.exit(1);
}
}
}
// Catches the exception in which the server cannot find a client
catch(IOException e) {
System.out.println("Failed to find a client");
System.exit(1);
}
}
}
Protocol.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Protocol {
private String username;
private String recipient;
private String sender;
private HashMap<String, ArrayList<String>> senderMap = new HashMap<String, ArrayList<String>>();
private HashMap<String, ArrayList<String>> messageMap = new HashMap<String, ArrayList<String>>();
// Stores the username for the logged in user
public void storeUsername(String user) {
username = user;
}
// Stores the recipient name
public void storeRecipient(String name) {
recipient = name;
}
// Returns how many messages the logged in user has
public int messagesNumber() {
if(messageMap.containsKey(username))
return messageMap.get(username).size();
else
return 0;
}
public boolean append(String recipient, String message) {
boolean success = false;
// If there is an entry for that name, just add the message to the end
if(messageMap.containsKey(recipient)) {
senderMap.get(recipient).add(username);
messageMap.get(recipient).add(message);
success = true;
}
// If there is no entry for that name, create a new entry with a list of messages and add the first message
else {
senderMap.put(recipient, new ArrayList<String>());
senderMap.get(recipient).add(username);
messageMap.put(recipient, new ArrayList<String>());
messageMap.get(recipient).add(message);
success = true;
}
return success;
}
public String readSender() {
// If the user has an entry and has at least 1 sender, return the least recent sender and then remove it (the sender first in the list)
if(senderMap.containsKey(username)) {
if(senderMap.get(username).size() > 0) {
String temp = senderMap.get(username).get(0);
senderMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
public String readMessage() {
// If the user has an entry and has at least 1 unread message, return the least recent unread message and then remove it (the first message in the list)
if(messageMap.containsKey(username)) {
if(messageMap.get(username).size() > 0) {
String temp = messageMap.get(username).get(0);
messageMap.get(username).remove(0);
return temp;
}
else
// If there are no messages left to read
return "NO MESSAGES";
}
else
// If the login hasn't been created yet
return "NO MESSAGES";
}
}
I am trying to do an extra credit assignment for my Java class where we are attempting to hack into a server. The problem I am having right now is only sending one password at a time:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private static int passwordLength;
private static String attempt;
private static int counter = 0;
private static String acceptable = "ABCDEFGHIJKLMNOPQRSTUVWXYXZabcdefghijklmnopqrstuvwxyz0123456789";
public Client()
{
try
{
System.out.println("Connecting to server...");
socket = new Socket("localhost", 58999);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Run the server first.");
}
}
public void close()
{
try
{
socket.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
public String sendPassword(String pass)
{
if (!HUSH) System.out.print("Sending: " + pass);
out.println(pass);
String result = null;
try
{
result = in.readLine();
if (!HUSH)
{
if (result.equals("no"))
System.out.println(" (wrong password)");
else if (result.equals("yes"))
System.out.println(" (CORRECT!)");
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return result;
}
public static boolean HUSH = false;
public static void main(String[] args)
{
Client me = new Client();
//BEGIN YOUR WORK
int length;
HUSH = false; //change this to false for testing
System.out.println("Input character length");
Scanner ui = new Scanner(System.in);
length = ui.nextInt();
Client(length);//set the max length of the password
generate();//pull into the first generate method
me.sendPassword("1234");
me.sendPassword(attempt); //the first password i am trying to break
me.sendPassword("letmein");
me.sendPassword("willthiswork");
// END YOUR WORK
me.close();
}
public static void Client(int max)
{
passwordLength = max;
}
public static void generate()
{
generate(""); //enters generate(String password)
}
static void generate(String password)
{
//base case
if(password.length() == passwordLength)//if password is long enough
System.out.println(++counter + " " + password);
else
for(int x = 0; x < acceptable.length(); x++)
generate(attempt = password + acceptable.charAt(x));
}
}
When I run the code (using the server that is supplied), it runs every possible password combination, but returns 9 (passwordLength number of times) instead of sending say..... A (wrong password) B (wrong password) so on and so forth. I know I need to add something onto my for loop to call it back to main, but I'm not sure how to.
This is one of the most common application scenario that can be found all over the net. and I'm not asking any questions about the java codes that I did because I was successful in running it on my laptop where both the client and server part of the .java file resides. Rather I have had problem getting it to work in between two computers. I tried establishing physical connection using cross-over cable to connect two computers, and did a test to see if file transfers successfully and it did, however, keeping one Server part of the .java file in one computer and client part in the other, I tried to run the server first and then the client but it got a "access denied" error.
For reference here's my two .java files:
/* ChatClient.java */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ChatClient {
private static int port = 5000; /* port to connect to */
private static String host = "localhost"; /* host to connect to (server's IP)*/
private static BufferedReader stdIn;
private static String nick;
/**
* Read in a nickname from stdin and attempt to authenticate with the
* server by sending a NICK command to #out. If the response from #in
* is not equal to "OK" go bacl and read a nickname again
*/
private static String getNick(BufferedReader in,
PrintWriter out) throws IOException {
System.out.print("Enter your nick: ");
String msg = stdIn.readLine();
out.println("NICK " + msg);
String serverResponse = in.readLine();
if ("SERVER: OK".equals(serverResponse)) return msg;
System.out.println(serverResponse);
return getNick(in, out);
}
public static void main (String[] args) throws IOException {
Socket server = null;
try {
server = new Socket(host, port);
} catch (UnknownHostException e) {
System.err.println(e);
System.exit(1);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
/* obtain an output stream to the server... */
PrintWriter out = new PrintWriter(server.getOutputStream(), true);
/* ... and an input stream */
BufferedReader in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
nick = getNick(in, out);
/* create a thread to asyncronously read messages from the server */
ServerConn sc = new ServerConn(server);
Thread t = new Thread(sc);
t.start();
String msg;
/* loop reading messages from stdin and sending them to the server */
while ((msg = stdIn.readLine()) != null) {
out.println(msg);
}
}
}
class ServerConn implements Runnable {
private BufferedReader in = null;
public ServerConn(Socket server) throws IOException {
/* obtain an input stream from the server */
in = new BufferedReader(new InputStreamReader(
server.getInputStream()));
}
public void run() {
String msg;
try {
/* loop reading messages from the server and show them
* on stdout */
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
and here's the ChatServer.java:
/* ChatServer.java */
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Hashtable;
public class ChatServer {
private static int port = 5000; /* port to listen on */
public static void main (String[] args) throws IOException
{
ServerSocket server = null;
try {
server = new ServerSocket(port); /* start listening on the port */
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
System.exit(1);
}
/* start a new thread to handle this client */
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ChatServerProtocol {
private String nick;
private ClientConn conn;
/* a hash table from user nicks to the corresponding connections */
private static Hashtable<String, ClientConn> nicks =
new Hashtable<String, ClientConn>();
private static final String msg_OK = "OK";
private static final String msg_NICK_IN_USE = "NICK IN USE";
private static final String msg_SPECIFY_NICK = "SPECIFY NICK";
private static final String msg_INVALID = "INVALID COMMAND";
private static final String msg_SEND_FAILED = "FAILED TO SEND";
/**
* Adds a nick to the hash table
* returns false if the nick is already in the table, true otherwise
*/
private static boolean add_nick(String nick, ClientConn c) {
if (nicks.containsKey(nick)) {
return false;
} else {
nicks.put(nick, c);
return true;
}
}
public ChatServerProtocol(ClientConn c) {
nick = null;
conn = c;
}
private void log(String msg) {
System.err.println(msg);
}
public boolean isAuthenticated() {
return ! (nick == null);
}
/**
* Implements the authentication protocol.
* This consists of checking that the message starts with the NICK command
* and that the nick following it is not already in use.
* returns:
* msg_OK if authenticated
* msg_NICK_IN_USE if the specified nick is already in use
* msg_SPECIFY_NICK if the message does not start with the NICK command
*/
private String authenticate(String msg) {
if(msg.startsWith("NICK")) {
String tryNick = msg.substring(5);
if(add_nick(tryNick, this.conn)) {
log("Nick " + tryNick + " joined.");
this.nick = tryNick;
return msg_OK;
} else {
return msg_NICK_IN_USE;
}
} else {
return msg_SPECIFY_NICK;
}
}
/**
* Send a message to another user.
* #recepient contains the recepient's nick
* #msg contains the message to send
* return true if the nick is registered in the hash, false otherwise
*/
private boolean sendMsg(String recipient, String msg) {
if (nicks.containsKey(recipient)) {
ClientConn c = nicks.get(recipient);
c.sendMsg(nick + ": " + msg);
return true;
} else {
return false;
}
}
/**
* Process a message coming from the client
*/
public String process(String msg) {
if (!isAuthenticated())
return authenticate(msg);
String[] msg_parts = msg.split(" ", 3);
String msg_type = msg_parts[0];
if(msg_type.equals("MSG")) {
if(msg_parts.length < 3) return msg_INVALID;
if(sendMsg(msg_parts[1], msg_parts[2])) return msg_OK;
else return msg_SEND_FAILED;
} else {
return msg_INVALID;
}
}
}
class ClientConn implements Runnable {
private Socket client;
private BufferedReader in = null;
private PrintWriter out = null;
ClientConn(Socket client) {
this.client = client;
try {
/* obtain an input stream to this client ... */
in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
/* ... and an output stream to the same client */
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.err.println(e);
return;
}
}
public void run() {
String msg, response;
ChatServerProtocol protocol = new ChatServerProtocol(this);
try {
/* loop reading lines from the client which are processed
* according to our protocol and the resulting response is
* sent back to the client */
while ((msg = in.readLine()) != null) {
response = protocol.process(msg);
out.println("SERVER: " + response);
}
} catch (IOException e) {
System.err.println(e);
}
}
public void sendMsg(String msg) {
out.println(msg);
}
}
Now, what should I do in order to run this two files from two computers given that I have the physical connection(TCP/IP) setup already??
Thanks in advance... :)
Sounds like it's quite possibly a firewall problem. Have you tried opening a hole in your firewall for port 1001?
Have you also looked at your java.policy and make sure that it is configured to allow local codebase to open sockets?
as mentioned in comment, you should not use port < 1025 for you applications, since they are always used in deamon processes. However you should test your program like this
1) if you get connection refused then you should check the exception properly, whether client program takes time before generating exception ( that mean request is going to server and then it's giving connection refused), in that case you should try java.policy put following in a file named java.policy
grant {
permission java.net.SocketPermission ":1024-65535",
"connect,accept";
permission java.net.SocketPermission ":80", "connect";
permission java.io.FilePermission "", "read,write,delete";
permission java.security.SecurityPermission "";
};
while compiling use this flag -Djava.security.policy=java.policy
more-over you should also try -Djava.rmi.server.hostname=IP, where IP is clien-ip for client.java and server-ip for server.java
2) if you are immediately getting exception at client side then your request is not going outside your pc, so client has some problem.
check the exception properly and post them over here.
3) though i've not got access denied error, but it seems to have port problem that might be solved using policy or port>1024.
post what are you getting now.