我已经在java中创建了一个Client / Server程序,我已经完全按照我的意愿使用cmd了,现在我正在尝试将代码的客户端转换为GUI,但是我在打印时遇到问题客户端消息和从文本字段和服务器消息中读取客户端输入,这是我到目前为止所做的,我在编译时没有错误,但gui它自己没有运行,任何帮助表示赞赏。 这是客户端代码:
import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;
public class TcpClient
{
public static void main(String[] args)
{
try
{
new TcpClient().start();
}
catch(Exception e)
{
System.out.println("Major Error" + e.getMessage());
e.printStackTrace();
}
}
public void start() throws IOException
{
JFrame build = new JFrame("Client");
JTextField serv = new JTextField();
JTextField clie = new JTextField();
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serv.setBounds(50,210,300,50);
build.add(serv);
clie.setBounds(350,210,300,50);
build.add(clie);
//=====================================================================
Socket clientSocket = null;
InetAddress hostA = null;
PrintWriter clientOutput = null;
BufferedReader clientInput = null;
BufferedReader standardInput = null;
try
{
hostA = InetAddress.getLocalHost();
clientSocket = new Socket(hostA.getHostName(), 5600);
clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientOutput = new PrintWriter(clientSocket.getOutputStream(), true);
standardInput = new BufferedReader(new InputStreamReader(System.in));
String serverMsg, clientMsg;
//read from a socket and respond back to server
while((serverMsg = clientInput.readLine()) != null)
{
serv.setText("Server Saying - " + serverMsg);
if(serverMsg.equals("exit"))
break;
clientMsg = standardInput.readLine();
if(clientMsg != null)
{
clie.setText("Client Saying - " + clientMsg);
clientOutput.println(clientMsg);
}
}
}
catch(UnknownHostException e)
{
System.exit(1);
}
catch(IOException e)
{
System.exit(1);
}
finally
{
//clean up time
clientOutput.close();
clientInput.close();
standardInput.close();
clientSocket.close();
}
//=====================================================================
build.setLayout(null);
build.setSize(700,600);
build.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
build.setVisible(true);
build.setResizable(false);
}
}
答案 0 :(得分:2)
如评论中所述,您应该学习多线程,尤其是EDT
现在正在发生的是您的代码和GUI,并阻止彼此正常工作。通过在EDT上运行GUI,您的应用程序可以在不停止GUI的情况下运行。当应用程序的报告更改与您的GUI相关时,您可以在时机成熟时通知EDT。