Java Socket基础[备忘]
1.服务端----Server.java
import javax.swing.*; import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; /** * Created by JXJ on 2017/6/26. */ public class Server extends JFrame{ private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private ServerSocket server; private Socket connection; //构造方法 public Server(){ super("即时聊天小程序"); userText=new JTextField(); userText.setEditable(false); userText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(e.getActionCommand()); userText.setText(""); } }); add(userText,BorderLayout.NORTH); chatWindow=new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300,150); setVisible(true); } //建立并启动服务 public void startRununing(){ try{ server=new ServerSocket(6789,100); while(true){ try{ //等待连接 waitForConnect(); //获取输入输出数据流 setupStreams(); //聊天 whileChatting(); }catch (EOFException eofException){ showMessage("\n 连接已经结束!"); }finally { closeCrap(); } } }catch (IOException ioException){ ioException.printStackTrace(); } } //等待连接,然后显示连接信息 private void waitForConnect() throws IOException{ showMessage(" 等待客户端连接...\n"); connection=server.accept(); showMessage("客户端"+connection.getInetAddress().getHostName()+"已连接!\n "); } //获取输入输出流 private void setupStreams() throws IOException{ output=new ObjectOutputStream(connection.getOutputStream()); //这个重点关注一下 output.flush(); input=new ObjectInputStream(connection.getInputStream()); showMessage("\n数据流已建立!\n "); } //聊天信息处理 private void whileChatting() throws IOException { String message="现在你已经连接上了!"; sendMessage(message); ableToType(true); do{ try{ message=(String)input.readObject(); showMessage(message+"\n "); }catch (ClassNotFoundException classNotFoundException){ showMessage("用户发送信息转换异常!\n"); } }while(!message.equals("client-end")); } //聊天结束后关闭输入输出流和socket private void closeCrap() { showMessage("正在关闭连接...\n"); ableToType(false); try{ //注意关闭先后顺序 输出流 输入流 socket output.close(); input.close(); connection.close(); }catch (IOException ioException){ } } //给客户端发送信息 private void sendMessage(String message) { try{ output.writeObject("Server"+message); output.flush(); showMessage("Server"+message+"\n"); }catch (IOException ioException){ chatWindow.append("[错误] 我没有成功发送信息!"); } } //在窗口上实时显示聊天信息 private void showMessage(final String text) { //注意窗口更新信息的方式 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { chatWindow.append(text); } }); } //让用户输入信息 private void ableToType(final boolean tof) { //注意按钮的禁用与启用的方式 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userText.setEditable(tof); } }); } }
2.服务端测试----ServerTest.java
/** * Created by JXJ on 2017/6/26. */ import javax.swing.JFrame; public class ServerTest { public static void main(String[] args){ Server server=new Server(); server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); server.startRununing(); } }
3.客户端----Client.java
/** * Created by JXJ on 2017/6/26. */ 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 ObjectInputStream input; private ObjectOutputStream output; private String message=""; private String serverIP; private Socket connection; //构造方法 public Client(String host){ super("客户端"); serverIP=host; userText=new JTextField(); userText.setEditable(false); userText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendMessage(e.getActionCommand()); userText.setText(""); } }); add(userText,BorderLayout.NORTH); chatwindow=new JTextArea(); add(new JScrollPane(chatwindow),BorderLayout.CENTER); setSize(300,150); setVisible(true); } //建立连接 public void startRununing(){ try{ connectToServer(); setupStreams(); whileChatting(); }catch (EOFException eofException){ showMessage("客户端断开连接! \n"); }catch (IOException ioExceptiopn){ ioExceptiopn.printStackTrace(); } finally { closeCrap(); } } //连接到服务端 private void connectToServer() throws IOException { showMessage("正在尝试连接服务端... \n"); connection=new Socket(InetAddress.getByName(serverIP),6789); showMessage("已连接至"+connection.getInetAddress().getHostName()); } //建立输入输出流 private void setupStreams() throws IOException { output=new ObjectOutputStream(connection.getOutputStream()); output.flush(); input=new ObjectInputStream(connection.getInputStream()); showMessage("已创建输入输出流... \n"); } //聊天信息处理 private void whileChatting() throws IOException { ableToType(true); do{ try{ message=(String)input.readObject(); showMessage(message+"\n"); }catch (ClassNotFoundException classNotFoundException){ showMessage(" 未知的输入对象类型\n"); } }while(!message.equals("server-end")); } //关闭输入输出流和socket private void closeCrap() { showMessage("关闭客户端连接资源\n"); ableToType(false); try{ output.close(); input.close(); connection.close(); }catch (IOException ioException){ ioException.printStackTrace(); } } //给服务端发送信息 private void sendMessage(String message) { try{ output.writeObject("client-"+message); output.flush(); showMessage("client-"+message+"\n"); }catch (IOException ioException){ showMessage("客户端发送数据失败\n"); } } //在窗口上实时显示聊天信息 private void showMessage(final String text) { //注意窗口更新信息的方式 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { chatwindow.append(text); } }); } //让用户输入信息 private void ableToType(final boolean tof) { //注意按钮的禁用与启用的方式 SwingUtilities.invokeLater(new Runnable() { @Override public void run() { userText.setEditable(tof); } }); } }
4.客户端测试----ClientTest.java
import javax.swing.*; /** * Created by JXJ on 2017/6/26. */ public class ClientTest { public static void main(String[] args){ Client client=new Client("127.0.0.1"); client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); client.startRununing(); } }
【路漫漫其修远兮,吾将上下而求索】
posted on 2017-06-29 21:24 binghuojxj 阅读(214) 评论(0) 编辑 收藏 举报