Доступ к переменной из другого класса
Уже битую неделю я пытаюсь заставить мой код достать recievedData из ServerThread и отправить его в Main, чтобы потом записать его в JTextArea.
Пробовал и геттеры, и сеттеры, но к результату это меня не привело.
Main.java
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.ServerSocket;
public class Main extends ServerThread {
public static void main(String args[]){
JFrame main_frame = new JFrame();
JPanel main_panel = new JPanel();
main_frame.setSize(600,500);
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main_frame.setTitle("MessageBox");
main_frame.add(main_panel);
main_panel.setLayout(null);
JButton send_button = new JButton("Send");
send_button.setBounds(480,360,80,25);
main_panel.add(send_button);
JButton menu = new JButton("Menu");
menu.setBounds(480,390,80,25);
JFrame frame_menu = new JFrame();
JPanel panel_menu = new JPanel();
main_panel.add(menu);
frame_menu.setSize(400,400);
frame_menu.setTitle("Menu");
frame_menu.add(panel_menu);
panel_menu.setLayout(null);
JTextField TX_port = new JTextField(5);
TX_port.setBounds(20,20,45,20);
panel_menu.add(TX_port);
JLabel TX = new JLabel("TX:");
TX.setBounds(1,20,45,20);
panel_menu.add(TX);
JTextField RX_port = new JTextField(5);
RX_port.setBounds(20,50,45,20);
panel_menu.add(RX_port);
JLabel RX = new JLabel("RX:");
RX.setBounds(1,50,45,20);
panel_menu.add(RX);
JTextField send_text_field = new JTextField(30);
send_text_field.setBounds(20,360,450,25);
main_panel.add(send_text_field);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
main_panel.add(textArea);
JScrollPane textAreaPane = new JScrollPane(textArea);
textAreaPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
textAreaPane.setBounds(20,20,540,325);
main_panel.add(textAreaPane);
/*
Вот тут мне нужно получить доступ к переменной recievedData.
*/
send_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String sended_data=send_text_field.getText();
String sum = "TX: " + sended_data;
textArea.append(sum + "\n");
send_text_field.setText("");
}
});
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame_menu.setVisible(true);
frame_menu.setLocationRelativeTo(null);
}
});
main_frame.setVisible(true);
main_frame.setLocationRelativeTo(null);
}
}
SocketThread.java ---->ServerThread
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class ServerThread extends Thread
{
ServerSocket ss = null;
Socket s = null;
public ServerThread(ServerSocket sSocket)
{
ss = sSocket;
}
public void run()
{
InputStream is;
OutputStream os;
try
{
s = ss.accept();
}
catch(Exception ex)
{
stop();
}
System.out.println("Connected.");
try
{
is = s.getInputStream();
os = s.getOutputStream();
while(true)
{
String recievedData = recvString(is);
sendString(os, recievedData);
os.flush();
/*
Отсюда нужно достать recievedData
*/
System.out.println(recievedData);
if(recievedData.equals("quit"))
break;
}
is.close();
os.close();
}
catch(Exception ex)
{
stop();
}
try
{
s.close();
ss.close();
}
catch(Exception ex)
{
stop();
}
}
static void sendString(OutputStream os,
String s)
throws IOException
{
for(int i = 0; i < s.length(); i++)
{
os.write((byte)s.charAt(i));
}
os.write('\n');
os.flush();
}
static String recvString(InputStream is)
throws IOException
{
String szBuf = "";
int ch = is.read();
while (ch >= 0 && ch != '\n')
{
szBuf += (char)ch;
ch = is.read();
}
return szBuf;
}
}
SocketServer
import java.net.*;
public class SocketServer
{
public static void main(String args[])
{
System.out.println(
"* Socket Server *");
ServerSocket ss = null;
try
{
ss = new ServerSocket(9998);
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(0);
}
int nPort = ss.getLocalPort();
System.out.println(
"Local Port: " + nPort);
ServerThread sThread = null;
sThread = new ServerThread(ss);
sThread.start();
System.out.println(
"Waiting connection...");
try
{
sThread.join();
}
catch(InterruptedException ex)
{
System.out.println(ex.toString());
}
try
{
ss.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
System.exit(0);
}
}
SocketClient
package com.ooo;
import java.net.*;
import java.util.*;
import java.io.*;
import com.ooo.Main.*;
public class SocketClient{
public static void main(String args[]){
System.out.println(
"* Socket Client *");
Socket s = null;
try
{
s = new Socket("localhost", 9999);
}
catch(Exception ex)
{
System.out.println(ex.toString());
System.exit(0);
}
int nPort = s.getLocalPort();
System.out.println("Local Port: " + nPort);
InputStream is;
OutputStream os;
try
{
is = s.getInputStream();
os = s.getOutputStream();
String transievingData;
while(true)
{
transievingData = getKbdString();
sendString(os, transievingData);
os.flush();
if(transievingData.equals("quit"))
break;
transievingData = recvString(is);
System.out.println(transievingData);
}
is.close();
os.close();
s.close();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
static void sendString(OutputStream os,
String s)
throws IOException
{
for(int i = 0; i < s.length(); i++)
{
os.write((byte)s.charAt(i));
}
os.write('\n');
os.flush();
}
static String recvString(InputStream is)
throws IOException
{
String szBuf = "";
int ch = is.read();
while (ch >= 0 && ch != '\n')
{
szBuf += (char)ch;
ch = is.read();
}
return szBuf;
}
static public String getKbdString()
{
byte bKbd[] = new byte[256];
int iCnt = 0;
String szStr = "";
try
{
iCnt = System.in.read(bKbd);
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
szStr = new String(bKbd, 0, iCnt);
szStr = szStr.trim();
return szStr;
}
}
Run
package com.ooo;
class Run {
public static void main(final String ... args) throws InterruptedException {
Thread one = new Thread(() -> SocketServer.main(args));
Thread two = new Thread(() -> SocketClient.main(args));
one.start();
two.start();
one.join();
two.join();
}
}
Ответы (3 шт):
Сначала запустить RunServer, а затем RunClient
Main
import javax.swing.*;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static String t = "test";
public static String sendtext = "";
public static String text = "";
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
JFrame main_frame = new JFrame();
JPanel main_panel = new JPanel();
main_frame.setSize(600,500);
main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main_frame.setTitle("MessageBox");
main_frame.add(main_panel);
main_panel.setLayout(null);
JButton send_button = new JButton("Send");
send_button.setBounds(480,360,80,25);
main_panel.add(send_button);
JButton menu = new JButton("Menu");
menu.setBounds(480,390,80,25);
JFrame frame_menu = new JFrame();
JPanel panel_menu = new JPanel();
main_panel.add(menu);
frame_menu.setSize(400,400);
frame_menu.setTitle("Menu");
frame_menu.add(panel_menu);
panel_menu.setLayout(null);
JTextField TX_port = new JTextField(5);
TX_port.setBounds(20,20,45,20);
panel_menu.add(TX_port);
JLabel TX = new JLabel("TX:");
TX.setBounds(1,20,45,20);
panel_menu.add(TX);
JTextField RX_port = new JTextField(5);
RX_port.setBounds(20,50,45,20);
panel_menu.add(RX_port);
JLabel RX = new JLabel("RX:");
RX.setBounds(1,50,45,20);
panel_menu.add(RX);
JTextField send_text_field = new JTextField(30);
send_text_field.setBounds(20,360,450,25);
main_panel.add(send_text_field);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font(textArea.getFont().getFamily(), Font.BOLD, 15));
main_panel.add(textArea);
JScrollPane textAreaPane = new JScrollPane(textArea);
textAreaPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
textAreaPane.setBounds(20,20,540,325);
main_panel.add(textAreaPane);
Thread update = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if(!textArea.getText().equals(text))
textArea.setText(text);
send_button.setEnabled(!send_text_field.getText().isEmpty());
}
};
};
update.start();
send_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
sendtext = send_text_field.getText();
send_text_field.setText("");
}
});
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
frame_menu.setVisible(true);
frame_menu.setLocationRelativeTo(null);
}
});
main_frame.setVisible(true);
main_frame.setLocationRelativeTo(null);
}
}
RunClient
import javax.swing.JOptionPane;
public class RunClient {
public static void main(final String ... args) throws InterruptedException {
System.err.println("Frame: ");
Thread frame = new Thread(() -> Main.main(null));
frame.start();
String input = JOptionPane.showInputDialog("Username:");
if(input == null || input.isEmpty())
input = "User_" + System.nanoTime();
final String name = input;
System.err.println("SocketClient: ");
Thread two = new Thread(() -> SocketClient.main(name));
two.start();
two.join();
}
}
RunServer
public class RunServer {
public static void main(final String ... args) throws InterruptedException {
System.err.println("Frame: ");
Thread frame = new Thread(() -> Main.main(null));
frame.start();
Thread one = new Thread(() -> SocketServer.main(args));
one.start();
one.join();
}
}
ServerThread
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
class ServerThread extends Thread {
public static String username = "";
public static String text = "";
public static String sendtext = "Test";
ServerSocket ss = null;
Socket s = null;
public ServerThread(ServerSocket sSocket) {
ss = sSocket;
}
public void run() {
InputStream is;
OutputStream os;
try {
s = ss.accept();
} catch(Exception ex) {
stop();
}
System.out.println("Connected.");
try {
is = s.getInputStream();
os = s.getOutputStream();
String transievingData;
while(true) {
sendtext = "<Server> " + Main.sendtext;
if(Main.sendtext.isEmpty())
sendtext = "";
if(Main.sendtext.equals("quit"))
break;
Main.sendtext = "";
if(!sendtext.isEmpty()) {
System.err.println(sendtext);
Main.text += sendtext + "\n";
}
transievingData = sendtext;
sendString(os, transievingData);
os.flush();
transievingData = recvString(is);
if(!transievingData.isEmpty())
Main.text += transievingData + "\n";
if(!transievingData.isEmpty())
System.out.println(transievingData);
sendtext = "";
// sendtext = Main.sendtext;
// Main.sendtext = "";
//
// String recievedData = recvString(is);
// Main.text += recievedData + "\n";
// sendString(os, recievedData);
// os.flush();
// /*
// Отсюда нужно достать recievedData
// */
//
// System.out.println(recievedData);
//
// if(recievedData.equals("quit"))
// break;
}
is.close();
os.close();
} catch(Exception ex) {
stop();
}
try {
s.close();
ss.close();
} catch(Exception ex) {
stop();
}
}
static void sendString(OutputStream os, String s) throws IOException {
for(int i = 0; i < s.length(); i++) {
os.write((byte)s.charAt(i));
}
os.write('\n');
os.flush();
}
static String recvString(InputStream is) throws IOException {
String szBuf = "";
int ch = is.read();
while (ch >= 0 && ch != '\n') {
szBuf += (char)ch;
ch = is.read();
}
return szBuf;
}
}
SocketClient
import java.net.*;
import java.io.*;
public class SocketClient {
public static String username = "";
public static String text = "";
public static String sendtext = "Test";
public static void main(String username) {
SocketClient.username = username;
System.out.println("* Socket Client *");
Socket s = null;
try {
s = new Socket(InetAddress.getLocalHost(), 4040);
} catch(Exception ex) {
ex.printStackTrace();
System.exit(0);
}
int nPort = s.getLocalPort();
System.out.println("Local Port: " + nPort);
InputStream is;
OutputStream os;
try {
is = s.getInputStream();
os = s.getOutputStream();
sendString(os, username + " is join");
String transievingData;
while(true) {
sendtext = username + ": " + Main.sendtext;
if(Main.sendtext.isEmpty())
sendtext = "";
if(Main.sendtext.equals("quit")) {
sendString(os, username + " left server");
os.flush();
break;
}
Main.sendtext = "";
if(!sendtext.isEmpty()) {
Main.text += sendtext + "\n";
}
transievingData = getKbdString();
sendString(os, transievingData);
os.flush();
transievingData = recvString(is);
if(!transievingData.isEmpty())
Main.text += transievingData + "\n";
if(!transievingData.isEmpty())
System.out.println(transievingData);
sendtext = "";
// transievingData = getKbdString();
// if(!sendtext.isEmpty()) {
// System.out.println(sendtext);
// if(sendtext.toUpperCase().equals("EXIT")) {
// sendString(os, "Client left server");
// break;
// }
// sendString(os, sendtext);
// sendtext = "";
//// os.flush();
// }
//
// transievingData = recvString(is);
//
}
is.close();
os.close();
s.close();
} catch(Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
static void sendString(OutputStream os, String s) throws IOException {
for(int i = 0; i < s.length(); i++) {
os.write((byte)s.charAt(i));
}
os.write('\n');
os.flush();
}
static String recvString(InputStream is) throws IOException {
String szBuf = "";
int ch = is.read();
while (ch >= 0 && ch != '\n') {
szBuf += (char)ch;
ch = is.read();
}
return szBuf;
}
static public String getKbdString() {
// byte bKbd[] = new byte[256];
// int iCnt = 0;
// String szStr = "";
//
// try {
// iCnt = System.in.read(bKbd);
// } catch(Exception ex) {
// System.out.println(ex.toString());
// }
//
// szStr = new String(bKbd, 0, iCnt);
// szStr = szStr.trim();
return sendtext;
}
}
SocketServer
import java.net.*;
public class SocketServer {
public static void main(String args[]) {
System.out.println("* Socket Server *");
ServerSocket ss = null;
try {
ss = new ServerSocket(4040);
} catch(Exception ex) {
ex.printStackTrace();
System.exit(0);
}
int nPort = ss.getLocalPort();
System.out.println("Local Port: " + nPort);
ServerThread sThread = null;
sThread = new ServerThread(ss);
sThread.start();
System.out.println("Waiting connection...");
try {
sThread.join();
} catch(InterruptedException ex) {
ex.printStackTrace();
}
try {
ss.close();
} catch(Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
}
Проект:
src:
> Main.java
> RunClient.java
> RunServer.java
> ServerThread.java
> SocketClient.java
> SocketServer.java
Как я понял, Вам необходимо подключится к серверу, передать ему сообщение и принять ответное. Делается это через Socket.
Странно, что догадались сделать сервер, а клиент не смогли. Обычно всё наоборот происходит.
public class Main {
public static void main(String args[]) {
// подключиться к серверу
Socket clientSocket = new Socket("localhost", 9998); // заменить на реальные адрес и порт
// out для передачи
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// in для приёма
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
...
send_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
String sended_data = send_text_field.getText();
// передать сообщение на сервер
out.println(sended_data);
// принять сообщение с сервера
String received_data = in.readLine();
String sum = "TX: " + sended_data + '\n' +
"RX: " + received_data;
textArea.append(sum + "\n");
send_text_field.setText("");
}
});
...
}
}
На самом деле Вы предлагаете совершенно бредовую ситуацию сразу по нескольким аспектам, что правильно ответить просто не возможно.
Но тем не менее.
Самый простой способ.
Вы должны определить поле класса, в котором будет хранится сообщение. И использовать его вместо переменной. Тогда эти данные можно будет извлечь из класса.
class ServerThread extends Thread {
ServerSocket ss = null;
Socket s = null;
String receivedData;
...
public String getReceivedData() {
return receivedData();
}
...
public void run() {
...
while(true) {
recievedData = recvString(is);
sendString(os, recievedData);
}
...
}
...
}
Теперь можете смотреть, что там принимается.
String rd = sThread.getReceivedData();
или
String rd = sThread.receivedData;
В зависимости от того, сделаете геттер для поля или объявите поле доступным (public например)
Но там, где Вы обозначили своё желание получить эти данные - это просто полный бред.
Ничего Вы там никогда не получите и будите мучать форум дурацким вопросом, извините.
Минус, если что, не мой