我制作了两个简单的java程序:服务器聊天和客户端聊天。我没有在每个java文件的代码中看到任何错误,但是当我尝试将客户端程序连接到服务器程序时程序挂起。
这是服务器端代码:
package com.server;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection = null;
/**
* Creates new form sever
*/
public Server() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
startRunning();
}
//setup and run the server
public void startRunning(){
try{
//serversocket(port,queueLength)
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection!");
}finally{
closeCrap();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection
private void waitForConnection() throws IOException{
showMessage("Waiting for someone to connect...\n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress());
}
//get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are now setup!\n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = "SERVER - You are now connected! ";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n idk wtf the user sent!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets after chatting
private void closeCrap(){
showMessage("\n Closing connections...\n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}catch(NullPointerException nullPointerException){
showMessage("You are trying to close something not opened");
}
}
//send message to clients
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSEVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n Error: i cant send that message");
}
}
//updates chatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
//let the user type stuff
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
}
这是客户端代码:
package com.client;
import javax.swing.JOptionPane;
import java.sql.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
public class client extends javax.swing.JFrame {
Connection con;
int b;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP = "127.0.0.1";
private Socket connection;
public client() {
initComponents();
}
private void statusMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
startRunning();
}
//start chat system
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
eofException.printStackTrace();
showMessage("\n Client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeCrap();
}
}
//connect to server
private void connectToServer() throws IOException{
showMessage("\nAttempting connection...\n");
try{
connection = new Socket(InetAddress.getByName(serverIP),6789);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}catch(ConnectException connectException){
showMessage("IP not available or port busy");
}
}
//streams for seding and receiving
private void setupStreams() throws IOException{
try{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are good to go \n");
}catch(Exception e){
System.out.println("there was error with output or input");
}
}
//while chatting with server
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
System.out.println(message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n I dont know what that object is");
}catch(EOFException eofException){
showMessage("\nThere was an error with collecting input ");
}
}while(!message.equals("SERVER - END"));
}
//clos all stuff
private void closeCrap() {
showMessage("\n Closing connection...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send messages to server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n Something went wrong while sending message");
}
}
//showMessages
private void showMessage(final String m){
java.awt.EventQueue.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(m);
}
}
);
}
//allow typing
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
//showError
private void showError(String err){
String errMsg = err;
JOptionPane.showMessageDialog(null, errMsg, "Error", JOptionPane.ERROR_MESSAGE );
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new client().setVisible(true);
}
});
}
如果有人能够通过并给我一些关于如何纠正这一点的提示,我将非常高兴。
答案 0 :(得分:0)
我尝试了你的代码。我做过小修改:
似乎工作正常。
我对未来的建议是将服务器/客户端与GUI分开。 因此,您可以轻松地相互测试它们,并使其可移植以处理任何其他用户界面。
输出:
客户:showMessage
尝试连接...
client:showMessageConnected to:127.0.0.1
客户端:showMessage
溪流很好
客户端:showMessage
服务器 - 服务器 - 您现在已连接!
服务器 - 服务器 - 您现在已连接!
我附上代码供您参考。
服务器
reportViewer1_ReportExport
客户端:
ReportExport