import
java.io.*;
import
java.net.*;
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public
class
Server
extends
JFrame {
private
JTextField userText;
private
JTextArea chatwindow;
private
ObjectOutputStream output;
private
ObjectInputStream input;
private
ServerSocket server;
private
Socket connection;
//constructor
public
Server(){
super("My
Awesome Instant Messenger");
userText
= new
JTextField();
userText.setEditable(false);
userText.addActionListener(
new
ActionListener(){
public
void
actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText,BorderLayout.NORTH);
chatwindow
= new
JTextArea();
add(new
JScrollPane(chatwindow));
setSize(400,200);
setVisible(true);
}
//設置和運行server
public
void
startRunning(){
try{
server
= new
ServerSocket(6789,10); → 服務器端口(port)和多少人可以等待
while(true){
try{
//連接並有談話
waitForConnection();
→
等待有人連接服務器的函數
setupStreams();
→ 設置Stream可以接收和發送的函數
whileChatting();
→ 聊天時做什麼的函數
}catch(EOFException
eofException){ → 當連接結束例外處理
showMessage("\n
Server ended the connection");
}finally{
closeCrap();
}
}
}catch(IOException
ioException){
ioException.printStackTrace();
}
}
}
沒有留言:
張貼留言