?? chatclient.java
字號:
package chatroom;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.net.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class chatclient {
private JTextField textField;
private JTextArea textArea;
private JFrame frame;
private String host="localhost";
private int port=8000;
private static Socket socket;
BufferedReader in;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
static String clientsaid="";
/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
chatclient window = new chatclient();
window.frame.setVisible(true);
window.getResponse();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the application
*/
public chatclient() {
initialize();
try{
socket=new Socket(host,port);
Is = socket.getInputStream();
PS = new PrintStream(socket.getOutputStream());//獲取socket的輸出流
in = new BufferedReader(new InputStreamReader( Is));//獲取socket的輸入流
} catch (Exception e)
{textArea.append("無法連接服務器");}
}
public void sendRequest(String request)
{PS.println(request);
textArea.append("client發送請求:"+request+"\n");
}
public void getResponse(){
String str = new String();
str="wangba";
while(true)
{
try{
str=in.readLine();
if (str.equals(""))
str="wrong";
textArea.append("server說:"+str+"\n");
// if(str.equals("bye"))
// break;
} catch (IOException e){textArea.append("服務器中斷");}
//return str;
}
}
/**
* Initialize the contents of the frame
*/
private void initialize() {
frame = new JFrame();
frame.setName("frame_client");
frame.setTitle("client");
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 500, 375);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
textArea.setName("c_textroom");
textArea.setBounds(43, 39, 307, 155);
frame.getContentPane().add(textArea);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clientsaid=textField.getText();
{if (clientsaid==null)
clientsaid="";
}
sendRequest(clientsaid);
// getResponse();
}
});
button.setName("c_button");
button.setText("New JButton");
button.setBounds(359, 258, 99, 23);
frame.getContentPane().add(button);
textField = new JTextField();
textField.setName("c_text");
textField.setBounds(32, 258, 299, 37);
frame.getContentPane().add(textField);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -