import javax.swing.*;
import java.io.Serializable;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server implements Serializable{
public static void main(String[] args) {
String test1= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
int portnumber = tryParse(test1);
if (portnumber !=0) {
try {
Registry reg = LocateRegistry.createRegistry(portnumber); //Creates and exports a Registry instance on the local host that accepts requests
RmiImplementation imp = new RmiImplementation("C://ServerStorage");
reg.bind("remoteObject", imp);
System.out.println("Server is ready.");
System.out.println(portnumber);
} catch (Exception e) {
System.out.println("Server failed: " + e);
}
}
}
private static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (Exception e) {
return 0;
}
}
}
The above code helps me to set up my file server.
when the application is run, the dialog port number is requested.
If I type letters instead of numbers the program stops running, but I want it to continue and show me the dialog again.
Try with a do-while,
int portnumber = 0;
do {
String text= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
portnumber = tryParse(text);
}while(portnumber==0);
Related
Now I do realize there are lots of the same question but even after reading the answers I seem not to undertsand. So here is the code and I'll explain the problem.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server implements Runnable {
String firstName;
String lastName;
String password;
private ArrayList<ConnectionHandler> connections;
private ServerSocket server;
private boolean done;
private ExecutorService pool;
public Server() {
connections = new ArrayList<>();
done = false;
}
#Override
public void run() {
try {
server = new ServerSocket(9999);
pool = Executors.newCachedThreadPool();
while (!done) {
Socket client = server.accept();
ConnectionHandler handler = new ConnectionHandler((client));
connections.add(handler);
pool.execute(handler);
}
} catch (Exception e) {
shutdown();
}
}
public void shutdown() {
try {
done = true;
pool.shutdown();
if (!server.isClosed()) {
server.close();
}
for (ConnectionHandler ch : connections) {
ch.shutdown();
}
} catch (IOException e) {
// ignore
}
}
class ConnectionHandler implements Runnable {
private Socket client;
private BufferedReader in;
private PrintWriter out;
public void broadcast(String message) {
for (ConnectionHandler ch : connections) {
if (ch != null) {
ch.sendMessage(message);
}
}
}
public ConnectionHandler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
out = new PrintWriter((client.getOutputStream()), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out.println("To register type 1,to sign in type 2");
//TODO:for loop so only answer is 1 or 2
String message = in.readLine();
switch (message) {
case "1":
out.println("In order to register please enter your first and last name then set a password.");
out.println("Enter first name:");
firstName = in.readLine();
out.println("Enter last name:");
lastName = in.readLine();
out.println("Finally please set a password.");
password = in.readLine();
//TODO: add parameters for passcode
out.println("Now please type 2 to login");
message = in.readLine();
if (message.equals("2")) {
//TODO: copy paste from line 104-x
}
case "2":
out.println("Please enter your first name:");
String messageLogInFN= in.readLine();
out.println("Please enter your last name:");
String messageLogInLN = in.readLine();
out.println("Enter your password:");
String messageLogInPass = in.readLine();
boolean adminAccount = (messageLogInFN.equals("admin") && messageLogInLN.equals("admin") && messageLogInPass.equals("admin123cat"));
if (adminAccount) {
//TODO: add admin permissions
}
boolean Authentication = ((messageLogInFN.equals(firstName) && messageLogInLN.equals(lastName) && messageLogInPass.equals(password)));
if (Authentication) {
out.println("Welcome " + firstName + " " + lastName + "!");
System.out.println(firstName + " " + lastName + " has logged in." );
} else
out.println("Your name or password incorrect!");
}
} catch (IOException e) {
shutdown();
}
}
public void sendMessage(String message) {
out.println(message);
}
public void shutdown() {
try {
in.close();
out.close();
if (!client.isClosed()) {
client.close();
}
} catch (IOException e) {
//ignore
}
}
}
public static void main(String[] args) {
Server server = new Server();
server.run();
}
So I am learning java and saw a tutorial on youtube for a chat room, I programed it following the tutorial, and then I wanted to have a chat room with accounts so I got to coding. Now here is the thing even though I am able to have several devices connected to the server when 2 accounts register the server forgets the first one so there can only be 1 account at the same time. What I am trying to do is have an account system where everyone has their own account that they log in with their first name, last name and passwords. But it doesnt seem to work. How can I make it so that the server doesn't forget all accounts except for the last one that registered?
Edit: Here is the client code if it helps.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client implements Runnable {
private boolean done;
private Socket client;
private BufferedReader in;
private PrintWriter out;
#Override
public void run() {
try {
client = new Socket("127.0.0.1", 9999);
out = new PrintWriter((client.getOutputStream()), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
InputHandler inHandler = new InputHandler();
Thread t = new Thread(inHandler);
t.start();
String inMessage;
while ((inMessage = in.readLine()) != null) {
System.out.println(inMessage);
}
} catch (IOException e) {
shutdown();
}
}
public void shutdown() {
done = true;
try {
in.close();
out.close();
if(!client.isClosed()) {
client.close();
}
} catch (IOException e) {
//ignore
}
}
class InputHandler implements Runnable {
#Override
public void run() {
try {
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while (!done) {
String message = inReader.readLine();
if(message.equals("/quit")) {
out.println(message);
inReader.close();
shutdown();
} else {
out.println(message);
}
}
} catch (IOException e) {
shutdown();
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.run();
}
}
Also as I said most of this isnt my code and I followed a yt tutorial.
I wrote an applet which takes the MAC address from the local computer.
It works fine on eclipse but at the moment I try to run it via the browser it does not.
after some debugging i've come to realize that this part returns null on browser
InetAddress.getLocalHost();
Can anyone tell me why?
EDIT:
This is code I found somewhere on the web:
import java.applet.Applet;
import java.awt.Graphics;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class LoginApplet extends Applet {
private static final long serialVersionUID = 1L;
private String macAddress;
public void init() {
setMacAddress(getMacAddressFromClient());
}
public void paint(Graphics g)
{
String mac = getMacAddress();
if(mac.isEmpty())
{
mac = "Empty";
}
g.drawString(mac,15,15);
}
public String getMacAddressFromClient() {
String macAddr= "";
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
macAddress += addr.getHostAddress();
NetworkInterface dir = NetworkInterface.getByInetAddress(addr);
byte[] dirMac = dir.getHardwareAddress();
int count=0;
for (int b:dirMac){
if (b<0) b=256+b;
if (b==0) {
macAddr=macAddr.concat("00");
}
if (b>0){
int a=b/16;
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
a = (b%16);
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
}
if (count<dirMac.length-1)macAddr=macAddr.concat("-");
count++;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
macAddr=e.getMessage();
} catch (SocketException e) {
// TODO Auto-generated catch block
macAddr = e.getMessage();
}
return macAddr;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress += macAddress;
}
}
In eclipse: addr has the localhost address
In the browser (IE and chrome) addr is null.
My Java Applet works perfectly fine when I run from Netbeans and the jar file created works fine too. However, when I embed the applet into the browser, I have this error "RuntimeException java.lang.reflect.InvocationTargetException" I have surfed through to debug this error but I couldn't seem to find a solution for my codes. Please help. Thank You.
Here are my codes:
SerialTest.java (this is my main class, in the main method, I call the applet so that whatever that should be printed in the Java console will be printed in the applet instead)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Scanner;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/**
* The port we're normally going to use.
*/
public static final String PORT_NAMES[] = {
"/dev/cu.usbserial-A9014NQP" //, Mac OS X
//"/dev/ttyUSB0", // Linux
//"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader converting the
* bytes into characters making the displayed results codepage independent
*/
public BufferedReader input;
/**
* The output stream to the port
*/
public OutputStream output;
/**
* Milliseconds to block while waiting for port open
*/
public static final int TIME_OUT = 2000;
/**
* Default bits per second for COM port.
*/
public static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
//portnotdetected = "Could not find COM port.";
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port. This will prevent
* port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine = input.readLine().trim();
//String readID = inputLine.substring(1);
System.out.println("Read Tag ID: " + inputLine); //this is the tagID read
Connection conn = null;
try {
String userName = "root";
String password = "root";
String url = "jdbc:mysql://localhost:8889/RFID";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
//System.out.println("Database connection established");
Statement stmt = null;
ResultSet rs = null;
//SQL query command
String SQL = "SELECT * FROM Inventory WHERE (SerialID = '" + inputLine + "')";
//String SQL = "SELECT * FROM Inventory";
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
if (rs != null && rs.next()) {
String SerialID = rs.getString("SerialID");
String name = rs.getString("Name");
String description = rs.getString("Description");
if (inputLine.equals(SerialID)) {
System.out.println(SerialID + "\t " + name + "\t " + description + "\n"); //from Database
}
} else {
System.out.println("Sorry Tag ID " + inputLine + " not found database \n");
}
} catch (Exception e) {
System.err.println("Cannot connect to database server");
e.printStackTrace();
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
new SerialApp();
SerialTest main = new SerialTest();
main.initialize();
Thread t = new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {
Thread.sleep(1000000);
} catch (InterruptedException ie) {
}
}
};
t.start();
System.out.println("Started");
/*
Scanner scanner = new Scanner(System.in);
String userInput = scanner.next();
if ("q".equals(userInput)) {
System.exit(0);
}
*/
}
}
SerialApp.java (this is where I create my applet)
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class SerialApp extends JApplet implements Runnable, ActionListener
{
public JFrame frame;
public TextArea textArea;
public Thread reader;
public Thread reader2;
public boolean quit;
public final PipedInputStream pin=new PipedInputStream();
public final PipedInputStream pin2=new PipedInputStream();
Thread errorThrower; // just for testing (Throws an Exception at this Console
public void init() {
}
public SerialApp()
{
// create all components and add them
frame=new JFrame("RFID");
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
int x=(int)(frameSize.width/2);
int y=(int)(frameSize.height/2);
frame.setBounds(x,y,frameSize.width,frameSize.height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea=new TextArea();
textArea.setEditable(false);
Container container = getContentPane();// Get the content pane of the frame
container.setLayout(new BorderLayout());
container.add(textArea, BorderLayout.CENTER);
//Button button=new Button("clear"); //create button
/*
Panel panel=new Panel();
panel.setLayout(new BorderLayout());
panel.add(textArea,BorderLayout.CENTER);
//panel.add(button,BorderLayout.SOUTH); //button location
*/
frame.add(container);
frame.setVisible(true);
//button.addActionListener(this); //add button
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
}
public synchronized void actionPerformed(ActionEvent evt)
{
textArea.setText("");
}
public synchronized void run()
{
try
{
while (Thread.currentThread()==reader)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin.available()!=0)
{
String input=this.readLine(pin);
textArea.append(input);
}
if (quit) return;
}
while (Thread.currentThread()==reader2)
{
try { this.wait(100);}catch(InterruptedException ie) {}
if (pin2.available()!=0)
{
String input=this.readLine(pin2);
textArea.append(input);
}
if (quit) return;
}
} catch (Exception e)
{
textArea.append("\nConsole reports an Internal error.");
textArea.append("The error is: "+e);
}
// just for testing (Throw a Nullpointer after 1 second)
if (Thread.currentThread()==errorThrower)
{
try { this.wait(1000); }catch(InterruptedException ie){}
throw new NullPointerException("Application test: throwing an NullPointerException It should arrive at the console");
}
}
public synchronized String readLine(PipedInputStream in) throws IOException
{
String input="";
do
{
int available=in.available();
if (available==0) break;
byte b[]=new byte[available];
in.read(b);
input=input+new String(b,0,b.length);
}while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit);
return input;
}
}
applet.html
<html>
<head>
<title>Applet</title>
</head>
<body>
<applet code="SerialTest.class" archive="SerialApplet.jar" width="550" height="550">
</applet>
</body>
</html>
I have this error "RuntimeException
java.lang.reflect.InvocationTargetException"
This is because You are putting the applet code tag as :
<applet code="SerialTest.class" archive="SerialApplet.jar" width="550" height="550">
And SerialTest is not an Applet..Applets don't use a main method to execute. Instead they are started with their init() and start() methods. Have a look at the following official tutorial to know more about Applets : Java Applets
I have this error "RuntimeException
java.lang.reflect.InvocationTargetException"
Because , You are overruling the rules provided by sandbox of java Applet. I guess, gnu.io.SerialPort has something to do with this. Look at here to know more about applet sandbox: What Applets Can and Cannot Do
I have a the necessary RMI classes created, The client can send a message and it gets printed in the server window.
On the server i would like to read the message and for example if the message is equal to 100 then print out a message.
The problem being when i run the server i immediately get a null pointer exception. When i send the message 100 from the client to the server it prints the message but wont execute the if statement.
Interface:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface FileInterface extends Remote {
void message(String message) throws RemoteException;
}
Implementation:
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class FileImpl extends UnicastRemoteObject implements FileInterface {
private String name;
public FileImpl(String s) throws RemoteException {
super();
name = s;
}
public void message(String message) throws RemoteException{
System.out.println(message);
}
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
return(null);
}
}
}
Client:
import java.io.*;
import java.rmi.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class FileClient{
public static boolean loggedIn = false;
public static void main(String argv[]) {
try {
int RMIPort;
String hostName;
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the RMIRegistry host namer:");
hostName = br.readLine();
if( hostName.length() == 0 ) // if user did not enter a name
hostName = "localhost"; // use the default host name
System.out.println("Enter the RMIregistry port number:");
String portNum = br.readLine();
if( portNum.length() == 0 )
portNum = "1097"; // default port number
RMIPort = Integer.parseInt(portNum);
String registryURL = "rmi://" + hostName+ ":" + portNum + "/FileServer";
// find the remote object and cast it to an interface object
FileInterface fi = (FileInterface) Naming.lookup(registryURL);
System.out.println("Lookup completed " );
//System.out.println("File " + argv[0] + " Transfered" );
// invoke the remote method
boolean done = false;
//file.getName()
while( !done ) {
System.out.println("Enter Code: 100 = Login, 200 = Upload, 300 = Download, 400 = Logout: ");
String message = br.readLine();
boolean messageOK = false;
if( message.equals("100") ) {
messageOK = true;
System.out.println("Enter T-Number: (Use Uppercase 'T')");
String login = br.readLine();
if( login.charAt(0) == 'T' ) {
loggedIn = true;
fi.message("100");
System.out.println("Login Successful");
continue;
} else {
System.out.println("Login Error");
continue;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Server:
import java.io.*;
import java.rmi.*;
public class FileServer {
public static void main(String argv[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
FileInterface fi = new FileImpl("FileServer");
Naming.rebind("//localhost:1097/FileServer", fi);
System.out.println("Server Started...");
boolean done = false;
while( !done ) {
if ((msg.trim()).equals("100")) {
System.out.println("message recieved: 100 logged in");
} else {
System.out.println("Login Error");
}
}
} catch(Exception e) {
System.out.println("FileServer: "+e.getMessage());
e.printStackTrace();
}
}
}
Any help here would be appreciated.
I am using the following code to read some data from Android client. All is going fine. But now i am asked to make this server code non blocking. Is there any suggestions for this ? I was trying to use threads but dont know how ? I am beginner in Java :)
Thanks
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;
import javax.imageio.ImageIO;
public class Server {
//Server Constructor
public Server()
{}
//Variables Initialization
private static ServerSocket server;
byte[] imagetemp;
private static Socket socket1;
private static boolean newImage;
private static Sdfdata data;
private static boolean cond;
public static int port;
private static int number = 0;
//Image Availability return method
public boolean imageAvailable()
{
return newImage;
}
public boolean clientchk()
{
return socket1.isClosed();
}
//Image Flag set by Vis group when image read.
public void setImageFlag(boolean set)
{
newImage = set;
}
// Send the data to the Vis Group
public Sdfdata getData()
{
return data;
}
//Starts the Server
public static boolean start(int port1)
{
try {
port=port1;
server = new ServerSocket(port1);
System.out.println("Waiting for Client to Connect");
//New thread here
socket1=server.accept();
} catch (IOException e) {
System.out.println("Cannot Connect");
e.printStackTrace();
return false;
}
return true;
}
//Stops the Server
public boolean stop()
{
try {
socket1.close();
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// Starts the server
start(4444);
// DataInput Stream for reading the data
DataInputStream in = null;
try {
in = new DataInputStream(socket1.getInputStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
cond=true;
do {
try
{
//Read Image Data
int length = in.readInt();
//Create an ByteArray of length read from Client for Image transfer
Sdfdata data = new Sdfdata(length);
//for (int i=0; i<length; i++)
//{ data.image[i] = in.readbyte(); }
if (length > 0) {
in.readFully(data.image);
}
//Read Orientation
data.orientation[0] = in.readFloat(); //Orientation x
data.orientation[1] = in.readFloat(); //Orientation y
data.orientation[2] = in.readFloat(); //Orientation z
//Read GPS
data.longitude = in.readDouble();
data.latitude = in.readDouble();
data.altitude = in.readDouble();
//Display orientation and GPS data
System.out.println(data.orientation[0] + " " + data.orientation[1] + " " + data.orientation[2]);
System.out.println(data.longitude + " " + data.latitude + " " + data.altitude);
String fileName = "IMG_" + Integer.toString(++number) + ".JPG";
System.out.println("FileName: " + fileName);
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(data.image);
fos.close();
/*InputStream ins = new ByteArrayInputStream(data.image);
BufferedImage image = ImageIO.read(ins);
ImageIO.write(image, "JPG", new File (fileName));
*/
//set image flag
newImage = true;
} catch (Exception e) {
//System.out.println("EOF Or ? " + e);
cond =false;
socket1.close();
server.close();
start(port);
}
}while (cond);
}
}
Your code starts a server, waits for a connection, reads some data from the first connected client, and then exits after writing this data to a file.
Being asked to make your server "non-blocking" could mean that you are being asked to change it to use asynchronous IO (probably unlikely), or it could mean that you're being asked to handle more than one client at a time - because currently you can only serve one client and then your program exits.
This question is hard to answer because your current code is very far away from where you need it to be and it seems like some reading up on networking, sockets, and Java programming in general would be a good way to start.
I'd recommend Netty for doing anything network-related in Java and their samples and documentation are good and easy to follow. Good luck!