How to convert Python socket to Java? for Tello DJI drone - java

I am looking for a way to make the code that I wrote in Java work to soon develop an interface for the drone tello.
I have this java code:
package conexion;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Tello3 extends JFrame implements ActionListener, KeyListener, Runnable {
private static final long serialVersionUID = 1L;
private JLabel l1;
private JButton b1;
private JTextField tf1;
public Tello3() {
this.setLayout(null);
this.setTitle("Prueba 3");
//Panel - Panel
JPanel p = new JPanel();
p.setBounds(0, 0, 300, 150);
p.setLayout(null);
add(p);
//Textfield - Campo de texto
tf1 = new JTextField();
tf1.setBounds(10, 10, 280, 20);
tf1.addKeyListener(this);
tf1.setFocusable(true);
p.add(tf1);
//Labels - Etiquetas
l1 = new JLabel();
l1.setBounds(10, 50, 280, 20);
p.add(l1);
//Buttons - Botones
b1 = new JButton("Send");
b1.setBounds(80, 80, 140, 20);
b1.addActionListener(this);
b1.setFocusable(false);
p.add(b1);
Thread t = new Thread(this);
t.start();
}
public void Action() {
String command = tf1.getText();
try {
Socket s = new Socket("192.168.10.1", 8889);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(command);
dos.close();
if(command == "end") {
s.close();
}
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error3", 1);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error4", 1);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
Socket s = new Socket();
s.bind(new InetSocketAddress("", 9000));
//s.connect(new InetSocketAddress("", 9000));
} catch (IOException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e.getMessage(), "Error1", 1);
}
try {
ServerSocket ss = new ServerSocket(1518);
while(true) {
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
String returned = dis.readUTF();
l1.setText(returned);
dis.close();
if(returned == "end") {
ss.close();
}
}
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage(), "Error2", 1);
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getKeyCode() == 10) {
Action();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
Action();
}
public static void main(String[] arg0) {
JFrame form_tello = new Tello3();
form_tello.setSize(300, 150);
form_tello.setLocationRelativeTo(null);
form_tello.setResizable(false);
form_tello.setVisible(true);
form_tello.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
When I execute that just show a error 1 message with the bind, but I don't know if the rest of methods works.
The next code was written on python and works. It's officially from DJI.
#
# Tello Python3 Control Demo
#
# http://www.ryzerobotics.com/
#
# 1/1/2018
import threading
import socket
import sys
import time
host = ''
port = 9000
locaddr = (host,port)
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tello_address = ('192.168.10.1', 8889)
sock.bind(locaddr)
def recv():
count = 0
while True:
try:
data, server = sock.recvfrom(1518)
print(data.decode(encoding="utf-8"))
except Exception:
print ('\nExit . . .\n')
break
print ('\r\n\r\nTello Python3 Demo.\r\n')
print ('Tello: command takeoff land flip forward back left right \r\n up down cw ccw speed speed?\r\n')
print ('end -- quit demo.\r\n')
#recvThread create
recvThread = threading.Thread(target=recv)
recvThread.start()
while True:
try:
msg = raw_input();
if not msg:
break
if 'end' in msg:
print ('...')
sock.close()
break
if 'exit' in msg:
break
# Send data
msg = msg.encode(encoding="utf-8")
sent = sock.sendto(msg, tello_address)
except KeyboardInterrupt:
print ('\n . . .\n')
sock.close()
break
I'm working in Ubuntu 18.10 if that it's important and the drone connects with the smartphone.
If someone can help me convert the python code to java I will be grateful.

Related

How do I put a Server class on my website so my Client class can communicate with it from different computers?

I have a server client application working just how I want it locally. I need to get the server online so the client program can be used from different computers. Not sure how to do this. I have my own website that I thought I could just put the Server on in the background.
Is this possible or am I just looking at this the wrong way.
Server.java
package core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ArrayList<ClientHandler> clients = new ArrayList<>();
ServerSocket serverSocket = null;
int clientNum = 1; // keeps track of how many clients were created
// 1. CREATE A NEW SERVERSOCKET
try {
serverSocket = new ServerSocket(4444); // provide MYSERVICE at port
// 4444
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
// 2. LOOP FOREVER - SERVER IS ALWAYS WAITING TO PROVIDE SERVICE!
while (true) {
Socket clientSocket = null;
try {
// 2.1 WAIT FOR CLIENT TO TRY TO CONNECT TO SERVER
System.out.println("Waiting for client " + clientNum + " to connect!");
clientSocket = serverSocket.accept();
clientNum++;
ClientHandler c = new ClientHandler(clientSocket, clients);
clients.add(c);
// 2.2 SPAWN A THREAD TO HANDLE CLIENT REQUEST
Thread t = new Thread(c);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
// 2.3 GO BACK TO WAITING FOR OTHER CLIENTS
// (While the thread that was created handles the connected client's
// request)
} // end while loop
} // end of main method
} // end of class MyServer
class ClientHandler implements Runnable {
Socket s; // this is socket on the server side that connects to the CLIENT
ArrayList<ClientHandler> others;
Scanner in;
PrintWriter out;
ClientHandler(Socket s, ArrayList<ClientHandler> others) throws IOException {
this.s = s;
this.others = others;
in = new Scanner(s.getInputStream());
out = new PrintWriter(s.getOutputStream());
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
// 1. USE THE SOCKET TO READ WHAT THE CLIENT IS SENDING
while (true) {
String clientMessage = in.nextLine();
// System.out.println(clientMessage);
new Thread(new Runnable() {
#Override
public void run() {
try (PrintWriter fileWriter = new PrintWriter(new FileOutputStream(new File("chat.txt"), true));) {
fileWriter.println(clientMessage);
fileWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(others.size());
for (ClientHandler c : others) {
// System.out.println(c.toString());
c.sendMessage(clientMessage);
}
}
}).start();
}
}
private void sendMessage(String str) {
out.println(str);
out.flush();
}
} // end of class ClientHandler
ClientSide.java
package core;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class ClientSide extends JFrame {
private JPanel contentPane;
private JTextField textField;
private String name;
private JTextArea textArea;
private Thread serverListener;
private Socket socket;
private Scanner in;
private PrintWriter out;
// /**
// * Launch the application.
// */
// public static void main(String[] args) {
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// try {
// ClientSide frame = new ClientSide();
// frame.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// }
/**
* Create the frame.
*
* #throws IOException
*/
public ClientSide(String myName) {
try {
socket = new Socket("localhost", 4444);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
serverListener = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String clientMessage = in.nextLine();
try {
System.out.println("Receiving before dec: " + clientMessage);
clientMessage = Crypto.decrypt(clientMessage, "key");
System.out.println("Receiving after dec: " + clientMessage);
addLine(clientMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
serverListener.start();
name = myName;
setTitle("Client Side");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JPanel topPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) topPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
contentPane.add(topPanel);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(7);
topPanel.add(textArea);
JPanel bottomPanel = new JPanel();
contentPane.add(bottomPanel);
bottomPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel lblMessage = new JLabel("Message");
bottomPanel.add(lblMessage);
textField = new JTextField();
bottomPanel.add(textField);
textField.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// send string/message to server
String clientMessage;
try {
clientMessage = Crypto.encrypt(name + ": > " + textField.getText(), "key");
System.out.println("Sending: " + clientMessage);
out.println(clientMessage);
out.flush();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
bottomPanel.add(btnSend);
}
public void addLine(String text) {
textArea.setText(textArea.getText() + text + "\n");
}
}
Provided your ClientSide class connects with your server applicztion on port 4444, you can do the following:
Package your client as jar file and run on each computer you want to distribute it to.
Ensure, each of those computers have JRE installed.
3 Package your Server module as jar file
You should own your server or have admin right. So you can install Java if not there.
Depending on OS, SSH skill might be required
Ensure PORT 4444 is enabled on your host server. firewall
Get the public IP address of your server and use it in your ClideSide code.

Java Chat Application

I'm trying to make a MultiClient Chat Application in which the chat is implemented in the client window. I've tried server and client code for the same.one clint to server is running good but teo client to server is not running properly one clint communication good but second one client not giving response.
Client Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Clientchatform extends JFrame implements ActionListener {
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
String line;
BufferedReader br;
String response;
BufferedReader is ;
PrintWriter os;
public Clientchatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
Send.addActionListener(this);
conn = new Socket(InetAddress.getLocalHost(), 2000);
ChatHistory.setText("Connected to Server");
this.setTitle("Client");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
br= new BufferedReader(new InputStreamReader(System.in));
String line = is.readLine();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Server:"
+ line);
} catch (Exception e1) {
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "Me:"
+ NewMsg.getText());
try {
br= new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
ChatHistory.append(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
Clientchatform chatForm = new Clientchatform();
}
}
Server Code
package server1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class serverChatform extends JFrame implements ActionListener {
static ServerSocket server;
static Socket conn;
JPanel panel;
JTextField NewMsg;
JTextArea ChatHistory;
JButton Send;
//DataInputStream dis;
//DataOutputStream dos;
String line;
BufferedReader is ;
public serverChatform() throws UnknownHostException, IOException {
panel = new JPanel();
NewMsg = new JTextField();
ChatHistory = new JTextArea();
Send = new JButton("Send");
this.setSize(500, 500);
this.setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setLayout(null);
this.add(panel);
ChatHistory.setBounds(20, 20, 450, 360);
panel.add(ChatHistory);
NewMsg.setBounds(20, 400, 340, 30);
panel.add(NewMsg);
Send.setBounds(375, 400, 95, 30);
panel.add(Send);
this.setTitle("Server");
Send.addActionListener(this);
server = new ServerSocket(2000, 1, InetAddress.getLocalHost());
ChatHistory.setText("Waiting for Client");
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
while (true) {
try {
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream()));
PrintWriter os=new PrintWriter(conn.getOutputStream());
line=is.readLine();
ChatHistory.append(ChatHistory.getText() + 'n' + "Client:"
+ line);
} catch (Exception e1)
{
ChatHistory.setText(ChatHistory.getText() + 'n'
+ "Message sending fail:Network Error");
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if ((e.getSource() == Send) && (NewMsg.getText() != "")) {
ChatHistory.setText(ChatHistory.getText() + 'n' + "ME:"
+ NewMsg.getText());
try {
PrintWriter os =new PrintWriter(conn.getOutputStream());
os.println(NewMsg.getText());
os.flush();
} catch (Exception e1) {
try {
Thread.sleep(3000);
System.exit(0);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
NewMsg.setText("");
}
}
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
}
You're definitely on the right track, but I've got a question for you to ask yourself.
conn = server.accept();
// ServerThread st=new ServerThread(conn);
// st.start();
ChatHistory.setText(ChatHistory.getText() + 'n' + "Client Found");
How often is this code executed? Consider that of course the main(),
public static void main(String[] args) throws UnknownHostException,
IOException {
new serverChatform();
}
is only called once, and therefore only one serverChatform will ever be created.
As you seem to have written quite a bit of code yourself, and it therefore seems like you're ready to learn more, I'm not going to give a full solution, but merely a direction.
Once you accept a client, with conn = server.accept();, you will have to create another new serverChatform();. This has to happen in a different Thread though. How to do this, I leave as an exercise for you.
Each connected client has to be served in its own thread. Additionally you need a Thread that continiously listens for new clients to connect. That would look like this.
List<Socket> clients; // Save the socket for each client
[...]
new Thread(new Runnable(){
#Override
public void run() {
// Thread that runs forever listening for new clients
while(true){
Socket conn = server.accept();
// new client has connected, store its socket
clients.add(conn);
// and start new thread that interacts with this new client
new Thread(new Runnable(){
#Override
public void run() {
// SERVE CLIENT HERE!
}
}).start();
}
}
}).start();

Java socket: how the server can reads multiple lines from the client

I create chat app one to one by using Java programming language
I faced issue: client can't send a new message until he receives a message from the server.
You should have a multithreaded application.
The client will run 2 threads:
1) Sender thread which will run on send button. You can every time create a new instance of this thread on clicking send button.
2) The receiver thread will keep on running continuously and check the stream for any message. Once it gets a message on stream it will write the same on console.
Will update you shortly with the code.
Thanks
Written this code long back similarly you can write server using other port
package com.clients;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
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.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientFullDuplex extends JFrame implements ActionListener {
private JFrame jframe;
private JPanel jp1, jp2;
private JScrollPane jsp;
private JTextArea jta;
private JTextField jtf;
private JButton send;
private Thread senderthread;
private Thread recieverthread;
private Socket ds;
private boolean sendflag;
public static void main(String[] args) {
try {
ClientFullDuplex sfd = new ClientFullDuplex();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ClientFullDuplex() throws UnknownHostException, IOException {
initGUI();
ds = new Socket("127.0.0.1", 1124);
initNetworking();
}
public void initGUI() {
jframe = new JFrame();
jframe.setTitle("Client");
jframe.setSize(400, 400);
jp1 = new JPanel();
jta = new JTextArea();
jsp = new JScrollPane(jta);
jtf = new JTextField();
send = new JButton("Send");
send.addActionListener(this);
jp1.setLayout(new GridLayout(1, 2, 10, 10));
jp1.add(jtf);
jp1.add(send);
jframe.add(jp1, BorderLayout.SOUTH);
jframe.add(jsp, BorderLayout.CENTER);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta.append("hello client");
}
#Override
public synchronized void addWindowListener(WindowListener arg0) {
// TODO Auto-generated method stub
super.addWindowListener(arg0);
new WindowAdapter() {
#Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
if (ds != null)
try {
ds.close();
System.exit(0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public void initNetworking() {
try {
recieverthread = new Thread(r1);
recieverthread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Runnable r1 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Reciver Thread Started");
recieveMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()
+ "Sender Thread Started");
sendMessage(ds);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public void recieveMessage(Socket rms) throws IOException {
while (true) {
System.out.println(Thread.currentThread().getName()
+ "Reciver Functionality");
BufferedReader br = new BufferedReader(new InputStreamReader(
rms.getInputStream()));
String line = br.readLine();
System.out.println(line);
jta.append("\nServer:"+line);
}
}
public void sendMessage(Socket sms) throws IOException {
System.out.println(Thread.currentThread().getName()
+ "Sender Functionality");
PrintWriter pw = new PrintWriter(sms.getOutputStream(), true);
String sline = jtf.getText();
System.out.println(sline);
pw.println(sline);
jtf.setText("");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == send) {
senderthread = new Thread(r2);
senderthread.start();
}
}
}
This is the code I copied and edited from your earlier post.
The problem is that the input stream from socket is blocking. So my suggestion is to read up on async sockets in java and refactor the code below.
next to that it isn't that difficult to edit posts.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public static void main(String[] args) {
Server chatServer = new Server(5555);
System.out.println("###Start listening...###");
chatServer.startListening();
chatServer.acceptClientRequest();
}
private ServerSocket listeningSocket;
private Socket serviceSocket;
private int TCPListeningPort;
private ArrayList<SocketHanding> connectedSocket;
public Server(int TCPListeningPort)
{
this.TCPListeningPort = TCPListeningPort;
connectedSocket = new ArrayList<SocketHanding>();
}
public void startListening()
{
try
{
listeningSocket = new ServerSocket(TCPListeningPort);
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void acceptClientRequest()
{
try
{
while (true)
{
serviceSocket = listeningSocket.accept();
SocketHanding _socketHandling = new SocketHanding(serviceSocket);
connectedSocket.add(_socketHandling);
Thread t = new Thread(_socketHandling);
t.start();
System.out.println("###Client connected...### " + serviceSocket.getInetAddress().toString() );
}
}
catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class SocketHanding implements Runnable
{
private Socket _connectedSocket;
private PrintWriter socketOut;
private InputStream socketIn;
private boolean threadRunning = true;
private String rmsg;
public SocketHanding(Socket connectedSocket) throws IOException
{
_connectedSocket = connectedSocket;
socketOut = new PrintWriter(_connectedSocket.getOutputStream(), true);
socketIn = _connectedSocket.getInputStream();
}
private void closeConnection() throws IOException
{
threadRunning = false;
socketIn.close();
socketOut.close();
_connectedSocket.close();
}
public void sendMessage(String message)
{
socketOut.println(message);
}
private String receiveMessage() throws IOException
{
String t = "";
if (_connectedSocket.getInputStream().available() > 0)
{
byte[] b = new byte[8192];
StringBuilder builder = new StringBuilder();
int bytesRead = 0;
if ( (bytesRead = _connectedSocket.getInputStream().read(b)) > -1 )
{
builder.append(new String(b, 0, b.length).trim());
}
t = builder.toString();
}
return t;
}
#Override
public void run()
{
while (threadRunning)
{
try
{
rmsg = receiveMessage();
System.out.println(rmsg);
if(rmsg.equalsIgnoreCase("bye"))
{
System.out.println("###...Done###");
closeConnection();
break;
}
else
{
String smsg = "";
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
smsg = keyboard.readLine();
keyboard.close();
sendMessage("Server: "+smsg);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

Java Authentication Program Issue

I am new to programming, and created a little program to practice code. It is an authentication program where you type in a username and password, and only my specified username and password will work to make it show a picture. I typed all the code, and there was no error; but when I ran it and typed in the username and password, it failed to show the picture. Here is my code.
package main.Swing.com;
//imports
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.util.EventObject;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
//class that carries other classes and carries some variables
public class Main extends javax.swing.JFrame implements ActionListener, TextListener, InputMethodListener {
JButton Test = new JButton("TEST IF YOU HAVE ACCESS TO THIS");
JButton Cancel = new JButton("CANCEL");
JTextField username = new JTextField(15);
JTextField password = new JTextField(15);
String n = ("Nathan");
int nathannam;
int nathannamer;
JButton superman;
JButton supermanny;
//constructor class that has the jframe
public Main() {
super("Authenticator");
setSize(300, 220);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLookAndFeel();
//creating the pane and defining some labels
JPanel pane = new JPanel();
JLabel UsernameLabel = new JLabel("Username: ");
JLabel PasswordLabel = new JLabel("Password: ");
//adding all the components to the pane
pane.add(UsernameLabel);
pane.add(username);
pane.add(PasswordLabel);
pane.add(password);
pane.add(Test);
pane.add(Cancel);
//adding the pane
add(pane);
//adding a event listener to my JButton titled Test
Test.addActionListener(this);
//checking if the password variable and name variable are both
//correct by taking the values assigned to each of them later
//on in the code and adding them together and if they add together
//to the correct amount it should display a button, but it doesn't
//which is the problem I am having
if (nathannam + nathannamer == 24) {
ImageIcon superman = new ImageIcon("JButton.png");
JButton supermanny = new JButton(superman);
pane.add(supermanny);
}
//setting visibility to true
setVisible(true);
//end of constructor class
}
//start of class that checks if the username is correct
public void METHODPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if username is equivalent to my name which is nathan
if (source == Test) {
String get = username.getText().toString();
String notation = "Nathan";
//if it is equivalent a variable will be assigned to nathanam
for (int i = 0; i < get.length(); i++) {
if (get.substring(i) == notation) {
int nathannam = 14;
//if it is not it will assign a wrong variable to nathannam
} else {
int nathannam = 15;
}
}
}
}
//testing if password variable is correct
public void ACTIONPREFORMED(ActionListener evt) {
Object source = ((EventObject) evt).getSource();
//testing if password is correct
if (source == Test) {
String got = password.getText().toString();
String notition = "iamnathan";
//if it is equivalent a variable will be assigned to nathanamer
for (int i = 0; i < got.length(); i++) {
if (got.substring(i) == notition) {
int nathannamer = 10;
//if it is not equivalent nathannamer will be assigned a wrong variable
} else {
int nathannamer = 15;
}
}
}
} //setting the nimbus setlookandfeel that was implemented in java 7
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//adding the main method
public static void main(String[] args) {
setLookAndFeel();
Main main = new Main();
}
#Override
public void textValueChanged(TextEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void caretPositionChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
#Override
public void inputMethodTextChanged(InputMethodEvent event) {
// TODO Auto-generated method stub
}
}//end of program
You never call your test method from your implementation of actionPerformed(). Here's a much simplified version of your program that checks username when you click on TestAccess.
Going forward, see How to Use Password Fields for a working example of using JPasswordField.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
/**
* #see
*/
public class Test {
private final JTextField username = new JTextField(15);
private final JButton test = new JButton("Test access");
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
f.add(username);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("nathan".equalsIgnoreCase(username.getText()));
}
});
f.add(test);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Test().display();
});
}
}

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories