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");
}
在這個class中的所有的意義,比如Server一樣
沒有留言:
張貼留言