我创建了一个本地服务器和一个客户端窗口,以使它们在本地相互通信。
服务器和客户端都已创建。我的问题是我需要客户端在
中输入单词JTextField,我想将其传递到服务器。现在,当我检查输入的字符串时,它会显示
该字符串具有 NULL 值。
这是我的客户端代码:
import java.io.*;
import java.net.Socket;
import java.awt.event.*;
import javax.swing.*;
public class MyClientSide extends JFrame{
public static String userFile;
public static String entered = "";
public static String host = "localhost";
public static int port = 8080;
public static Socket socket = null;
public static DataOutputStream out = null;
public MyClientSide(){
JLabel jlbl = new JLabel("File Name: ");
final JTextField jtxt = new JTextField(20);
JButton jbtn = new JButton("Upload to Server");
JPanel jpnl = new JPanel();
jbtn.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {//Start of actionPerformed
entered = jtxt.getText();
}
});
jpnl.add(jlbl);
jpnl.add(jtxt);
jpnl.add(jbtn);
this.add(jpnl);
}
public MyClientSide(String error) {
// TODO Auto-generated constructor stub
JLabel jlbl = new JLabel("Please connect to server");
this.add(jlbl);
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String error = "Please connect to server";
MyClientSide connectFrm = new MyClientSide();
MyClientSide errorFrm = new MyClientSide(error);
try {
socket = new Socket(host,port);
connectFrm.setTitle("File Transfer Client");
connectFrm.setSize(500,80);
connectFrm.setVisible(true);
connectFrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
InputStreamReader(socket.getInputStream()));
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new DataOutputStream(socket.getOutputStream());
out.writeBytes(entered); /*Here is my problem. when I pass this to the server,
The value is NULL. I need to pass a string from
JTextField*/
}
catch (IOException e) {
errorFrm.setTitle("Error!!!!");
errorFrm.setSize(200,100);
errorFrm.setVisible(true);
errorFrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
System.err.print("Please connect to server");
}
}
}
感谢您的帮助
最佳答案
您的问题是您没有等待按下上传按钮!
你打电话
connectFrm.setVisible(true);
connectFrm.setDefaultCloseOperation(EXIT_ON_CLOSE);
但与此同时,您将继续与服务器进行通信。
请记住,JFrame
的 setVisible
不是阻塞调用。也就是说,无论对话框是否显示,无论按钮是否按下,它都会不停地直接执行下一个代码。
只有按下按钮后,您才需要与服务器通信。
即
在您的actionPerformed
函数中:
public void actionPerformed (ActionEvent e) {//Start of actionPerformed
entered = jtxt.getText();
sendToServer(entered);
}
然后创建一个名为sendToServer
的函数,只有在输入数据后才会调用该函数。
将您的 try/catch
block
try {
socket = new Socket(host,port);
..
在这个新函数中
关于java - java中如何将字符串传递到本地服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16126101/