import java.awt.Container;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.print.attribute.TextSyntax;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class javaSocket {
private JFrame frame;
private BufferedReader reader;
private ServerSocket server;
private Socket socket;
private JTextField textField;
private PrintWriter writer;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
javaSocket window = new javaSocket();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public javaSocket() {
initialize();
getserver();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
textField.setBounds(63, 169, 299, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
textArea = new JTextArea();
textArea.setBounds(76, 30, 286, 110);
frame.getContentPane().add(textArea);
}
void getserver()
{
try{
server=new ServerSocket(8999);
System.out.println("建立服务器套接字");
while(true)
{
System.out.println("等待连接");
socket=server.accept();
reader=new BufferedReader(new InputStreamReader(socket
.getInputStream()));
getCilentMessage();
}
}catch ( Exception e) {
e.printStackTrace();
}
}
private void getCilentMessage()
{
try{
while(true)
{
System.out.println("客户端:"+reader.readLine());
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(reader!=null)
{
reader.close();
}
if(socket!=null)
{
socket.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
private void connect()
{
textArea.append("尝试连接\n");
try{
socket=new Socket(host, port);
writer=new PrintWriter(socket.getOutputStream(),true);
textArea.append("成功连接\n");
}catch (Exception e) {
e.printStackTrace();
}
}
}