【发布时间】:2014-05-22 08:23:09
【问题描述】:
我有一个通过 Socket 与客户端创建 TCP 连接的服务器。由于我的应用程序应该是一个聊天,我需要服务器使用同一端口同时接受多个客户端,以便它们可以实时通信。 我的服务器端是一个 Java 应用程序,我的客户端是一个 Android 应用程序。
有可能做这样的事情吗?如果是,我该怎么做?
这是我的服务器代码:
public class Server {
public static void main(String[] args){
ServerClass server = new ServerClass();
server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
server.inizia();
}
}
public class ServerClass extends JFrame {
JTextArea testoarea;
String messaggio;
ObjectOutputStream output;
DataInputStream input;
ServerSocket server;
Socket connessione;
public ServerClass(){
super("Server in Ascolto");
testoarea = new JTextArea();
add(new JScrollPane(testoarea));
setSize(600, 700);
setVisible(true);
}
public void inizia()
{
try {
server = new ServerSocket(7100);
while(true)
{
try {
iniziaConnessione();
sistemaCanali();
chatta();
//closeCrap();
} catch (EOFException eofException) {
// TODO: handle exception
showMessage("Il Server ha perso la connessione..\n");
}
}
} catch (IOException ioException) {
// TODO: handle exception
ioException.printStackTrace();
}
}
private void iniziaConnessione() throws IOException {
// TODO Auto-generated method stub
showMessage("Aspetto qualcuno per connettermi.... \n");
connessione = server.accept();
showMessage("Mi sono connesso a qalcuno... \n");
}
private void sistemaCanali() throws IOException {
// TODO Auto-generated method stub
output = new ObjectOutputStream(connessione.getOutputStream());
output.flush();
input = new DataInputStream(connessione.getInputStream());
showMessage("I canali sono apposto... \n");
}
private void chatta() throws IOException {
// TODO Auto-generated method stub
String messaggio = "Sei connesso e pronto a chattare... \n";
showMessage(messaggio);
messaggio = (String) input.readUTF();
showMessage("Client - " + messaggio);
sendData(messaggio);
}
private void sendData(String messaggio2) {
// TODO Auto-generated method stub
try {
output.writeUTF(messaggio2);
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
showMessage("ERRORE: non riesco a inviare il messaggio... \n");
}
}
private void showMessage(final String text) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
testoarea.append(text);
}
}
);
}
}
【问题讨论】:
-
“有可能……”问题通常是修辞性的。如果您曾经使用过功能如此之多的软件(并且您曾经使用过!),那么这绝对是可能的。