【发布时间】:2017-04-15 16:49:11
【问题描述】:
这是我的服务器。顺便说一句,我正在使用 JFrame。实际上,当我在 pc 1 上运行服务器时,我有很多 pc,然后是 pc 2 和 pc 3 上的客户端。pc 3 客户端连接但服务器无法接收消息。虽然 pc 2 客户端已连接。
package server;
import java.net.*;
import java.io.*;
public class FrmServer extends javax.swing.JFrame {
ServerSocket providerSocket;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
//To run the connection
public void run(){
用于连接
try{
providerSocket = new ServerSocket(9090);
msgArea.append("Waiting for connection....");
connection = providerSocket.accept();
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendmessage("Connection is successful...");
while(true){
message = (String)in.readObject();
if(!message.isEmpty())
msgArea.append("\nClient: "+message);
}
}
catch(Exception e){
}
}
public void sendmessage(String msg){
try{
out.writeObject(msg);
out.flush();
msgArea.append("\nServer: "+msg);
}catch(Exception e){
}
}
/**
* Creates new form FrmServer
*/
public FrmServer() {
initComponents();
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendmessage(txt.getText());
}
public static void main(String args[]) {
FrmServer s = new FrmServer();
s.setVisible(true);
s.run();
}
客户
package client;
import java.net.*;
import java.io.*;
public class FrmClient extends javax.swing.JFrame {
Socket requestSocket;
ObjectInputStream in;
ObjectOutputStream out;
String message;
/**
* Creates new form FrmClient
*/
public FrmClient() {
initComponents();
}
public void run(){
try{
requestSocket = new Socket("10.99.225.12",9090);
msgArea.append("Connected to the server...");
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
while(true){
message = (String)in.readObject();
if(!message.isEmpty());
msgArea.append("\nServer: "+message);
}
}
catch(Exception e){
}
}
public void sendmessage(String msg){
try{
out.writeObject(msg);
out.flush();
msgArea.append("\nClient: "+msg);
}
catch(Exception e){
}
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
sendmessage(txt.getText());
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
try{
sendmessage("Got to go.. Goodbye!");
in.close();
out.close();
requestSocket.close();
}
catch(Exception e){
}
}
public static void main(String args[]) {
FrmClient c = new FrmClient();
c.setVisible(true);
c.run();
}
【问题讨论】:
-
您标记了 q 多线程。所以你显然已经知道答案了……
-
在tutorial的末尾,您可以找到一个简单的示例。
标签: java multithreading swing client-server java-io