import
java.io.*;
import
java.net.*;
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public
class
Client extends
JFrame{
private
JTextField userText;
private
JTextArea chatwindow;
private
ObjectOutputStream output;
private
ObjectInputStream input;
private
String message
= "";
private
String serverIP;
private
Socket connection;
//constructor
public
Client(String host){
super("Client
mofo!");
serverIP
= host;
userText
= new
JTextField();
userText.setEditable(false);
userText.addActionListener(
new
ActionListener(){
public
void
actionPerformed(ActionEvent event){
sendData(event.getActionCommand());
userText.setText("");
}
}
);
add(userText,
BorderLayout.NORTH);
chatwindow
= new
JTextArea();
add(new
JScrollPane(chatwindow),
BorderLayout.CENTER);
setSize(400,200);
setVisible(true);
}
//連接到服務器(Server)
public
void
startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException
eofException){
showMessage("\n
Client terminated connection");
}catch(IOException
ioException){
ioException.printStackTrace();
}finally{
closeCrap();
}
}
//connectToServer函數
private
void
connectToServer() throws
IOException{
showMessage("Attempting
connection...\n");
connection
= new
Socket(InetAddress.getByName(serverIP),6789);
showMessage("Connected
to:" +
connection.getInetAddress().getHostName());
}
//設置發送和接收消息的Stream
private
void
setupStreams() throws
IOException{
output
=new
ObjectOutputStream(connection.getOutputStream());
output.flush();
input
= new
ObjectInputStream(connection.getInputStream());
showMessage("\nyour
streams are now good to go");
}
//當與服務器聊天
private
void
whilechatting() throws
IOException{
ableTotype(true);
do{
try{
message
= (String) input.readObject();
showMessage("\n"
+ message);
}catch(ClassNotFoundException
classNotfoundException){
showMessage("\n
I don't know that object type");
}
}while(!message.equals("SERVER
- END"));
}
//關閉Streams和connection
private
void
closeCrap(){
showMessage("\n
closing crap down...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException
ioException){
ioException.printStackTrace();
}
}
//發送消息到服務器
private
void
sendData(String message){
try{
output.writeObject("CLIENT
- " + message);
output.flush();
showMessage("\nCLIENT
- " +message);
}catch(IOException
ioException){
chatwindow.append("\n
Can not send the message!");
}
}
}
在這個class中的所有的意義,比如Server一樣
在這個class中的所有的意義,比如Server一樣
沒有留言:
張貼留言