gpt4 book ai didi

通过互联网的java聊天程序

转载 作者:可可西里 更新时间:2023-11-01 02:57:00 28 4
gpt4 key购买 nike

<分区>

好吧,基本上我想做的是制作一个可以在 Internet 上运行的客户端服务器聊天程序,我已经完成了一个可以在 LAN 上完美运行的基本程序,但无法在 Internet 上正常运行..

服务器:

public class Server extends javax.swing.JFrame {


HashMap<String,PrintWriter> map = new HashMap<String,PrintWriter>();

ArrayList clientOutputStreams = new ArrayList();
ArrayList<String> onlineUsers = new ArrayList();
int port = 5080;
Socket clientSock = null;


public class ClientHandler implements Runnable {

BufferedReader reader;
Socket sock;
PrintWriter client;

public ClientHandler(Socket clientSocket, PrintWriter user) {
// new inputStreamReader and then add it to a BufferedReader
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
System.out.println("first");
} // end try
catch (Exception ex) {
System.out.println("error beginning StreamReader");
} // end catch
} // end ClientHandler()

@Override
public void run() {
System.out.println("run method is running");
String message;
String[] data;
String connect = "Connect";
String disconnect = "Disconnect";
String chat = "Chat";


try {
while ((message = reader.readLine()) != null) {
ta1.append(message + "\n");
ta1.repaint();
System.out.println("Received: " + message);
data = message.split("#");
for (String token : data) {

System.out.println(token);

}


System.out.println(data[data.length - 1] + " datalast");

if (data[2].equals(connect)) {

tellEveryone((data[0] + "#" + data[1] + "#" + chat));
userAdd(data[0]);
map.put(data[0], client);

} else if (data[2].equals(disconnect)) {
System.out.println("barpppppppppp");
tellEveryone((data[0] + "#has disconnected." + "#" + chat));
userRemove(data[0]);
map.remove(data[0]);

} else if (data[2].equals(chat)) {

tellEveryone(message);

} else {
System.out.println("No Conditions were met.");
}
} // end while
} // end try
catch (Exception ex) {

System.out.println("lost a connection");
System.out.println(ex.getMessage());

clientOutputStreams.remove(client);
} // end catch
} // end run()
}

public void go() {
// clientOutputStreams = new ArrayList();

try {
ServerSocket serverSock = new ServerSocket(port);
System.out.println("ServerSocket Created !");
System.out.println("Started listening to port " + port);

while (true) {
// set up the server writer function and then begin at the same
// the listener using the Runnable and Thread
clientSock = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
ta1.append(writer + " ");
ta1.repaint();
System.out.println(writer);

clientOutputStreams.add(writer);
//data_of_names_and_output_streams.add(writer.toString());


// use a Runnable to start a 'second main method that will run
// the listener
Thread listener = new Thread(new Server.ClientHandler(clientSock, writer));
listener.start();
System.out.println("Server Thread for 'new player' was started");
System.out.println("got a connection");
} // end while
} // end try
catch (Exception ex) {
System.out.println("error making a connection");
} // end catch

} // end go()

public void userAdd(String data) {
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.add(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);

for (String token : tempList) {

message = (token + add);
tellEveryone(message);
System.out.println(message);
}
tellEveryone(done);
}

public void userRemove(String data) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.remove(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);

for (String token : tempList) {

message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}

public void tellEveryone(String message) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
// jButton1.doClick();
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
if (message.length() < 250) {
System.out.println("inside it");

while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
// l1.setText(message);
System.out.println("Sending " + message);
writer.flush();
} // end try
catch (Exception ex) {
System.out.println("error telling everyone");
} // end catch

}

} else {
try {
clientSock.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

/**
* Creates new form Server
*/
public Server() {
initComponents();
ta1.repaint();
}

public static void main(String args[]) throws Exception {


UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");


/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
new Server().go();
}
} //end form

客户端:jbutton1 正在建立连接,jbutton2 发送消息。

public class Client extends javax.swing.JFrame {

boolean sent, receive;
SimpleDateFormat sdf;
String ip;
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;
DefaultListModel dlm;

public Client() {
initComponents();


dlm = (DefaultListModel) l1.getModel();

ip = JOptionPane.showInputDialog("Enter the IP of the server to connect");
}

public class IncomingReader implements Runnable {

public void run() {
String stream;
String[] data;
String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat", battlerequest = "battlerequest";

try {
while ((stream = reader.readLine()) != null) {

data = stream.split("#");
System.out.println(stream + " ------------------------ data");
if (data[2].equals(chat)) {

sdf = new SimpleDateFormat("HH:mm:ss");
t.append("(" + sdf.format(new Date()) + ") " + data[0] + ": " + data[1] + "\n");
//t.setText("<html><b>hi" + 3 + 3 + "</b></html>");
} else if (data[2].equals(connect)) {

t.removeAll();
userAdd(data[0]);

} else if (data[2].equals(disconnect)) {

userRemove(data[0]);

} else if (data[2].equals(done)) {

dlm.removeAllElements();
writeUsers();
userList.clear();
} else {
System.out.println("no condition met - " + stream);
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage() + " hi");
}
}
}
public void ListenThread() {
Thread IncomingReader = new Thread(new Client.IncomingReader());
IncomingReader.start();
}

public void userAdd(String data) {
userList.add(data);

}

public void userRemove(String data) {
t.setText(t1.getText() + data + " has disconnected.\n");
}

public void writeUsers() {
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token : tempList) {
//ul.append( token + "\n");
dlm.addElement(token);
// ul.setText(ul.getText() + token + '\n');
}
}

public void sendDisconnect() {

String bye = (username + "# #Disconnect");
try {
writer.println(bye); // Sends server the disconnect signal.
writer.flush(); // flushes the buffer
} catch (Exception e) {
t.append("Could not send Disconnect message.\n");
}

}

public void Disconnect() {

try {
t.append("Disconnected.\n");
sock.close();
} catch (Exception ex) {
t.append("Failed to disconnect. \n");
}
isConnected = false;
n.setEditable(true);
dlm.removeAllElements();
// ul.setText("");

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (isConnected == false && !n.getText().equals("")) {
username = n.getText();
n.setEditable(false);

try {
sock = new Socket(ip, 5080);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "#has connected.#Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
isConnected = true;
jLabel4.setText(n.getText());
//t.append( "<html><font color = \"black\"><b>Server : Welcome,</b></font></html>"+username);
//t1.setText("<html><font color=\"red\">yo</font></html>");
// Used to see if the client is connected.
} catch (Exception ex) {
t.append("Cannot Connect! Try Again. \n");
n.setEditable(true);
}
ListenThread();
} else if (isConnected == true) {
t.append("You are already connected. \n");
} else if (n.getText().equals("")) {
t.append("Enter a valid name \n");
}


}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if ((t1.getText()).equals(nothing)) {
t1.setText("");
t1.requestFocus();
} else {
try {
writer.println(username + "#" + t1.getText() + "#" + "Chat");
writer.flush(); // flushes the buffer
} catch (Exception ex) {
t.append("Message was not sent. \n");
}
t1.setText("");
t1.requestFocus();
}

t1.setText("");
t1.requestFocus(); // TODO add your handling code here:
}

private void dicsActionPerformed(java.awt.event.ActionEvent evt) {
sendDisconnect();
Disconnect(); // TODO add your handling code here:
}

我还转发了我将要使用的端口 - 即。 5080

setting up virtual servers

现在当我的 friend 在他家里的电脑上打开客户端程序时,我告诉他输入 192.168.1.2 作为 ip,因为这就是我打开 cmd 并输入 ipconfig 时保存的内容....

setting of network connection

有时我认为我给他的 IP 地址是错误的,因为我猜 192.168.1.2 是局域网或内部 IP 地址,那么,我也这样做吗?我在哪里可以获得正确的 ip 地址?还是我的代码有其他问题?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com