Java Socket驱动如何才能变得***?其实只要掌握好相关的代码就可以把相关的一起搞定,下面我们就看看在Java Socket驱动中的关键代码,希望大家有所收获。那么我们首先来看看各种接口上的知识。
由于是基于事件Java Socket驱动的组件,所以MySingleThreadServer1类要继承ActionListener接口,实现该接口唯一的方法actionPerformed(ActionEvent e),即当触发某一事件时,执行该方法内的代码。关键代码如下:
复制
public class MySingleThreadServer1 implements
ActionListener{ private Frame f; private TextArea ta1 = newTextArea("",5,40,TextArea.
SCROLLBARS_VERTICAL_ONLY); private TextArea ta2 = new TextArea("",16,52,TextArea.
SCROLLBARS_VERTICAL_ONLY); private Button b; private String msg =""; OutputStream os; DataOutputStream dos; InputStream is; DataInputStream dis; ServerSocket ss; Socket s; public MySingleThreadServer1(){ f = new Frame("server:小马"); b = new Button("服务器发送"); f.setBackground(Color.WHITE); b.setBackground(Color.LIGHT_GRAY); ta1.setBackground(Color.LIGHT_GRAY); ta2.setBackground(Color.LIGHT_GRAY); ta2.setEditable(false); //set to only be read f.setLayout(new FlowLayout(FlowLayout.LEFT)); f.add(ta1); f.add(b); f.add(ta2); f.setLocation(200,200); f.setSize(400,400); f.setResizable(false); f.setVisible(true); b.addActionListener(this); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); try{ ss = new ServerSocket(7777); s = ss.accept(); is = s.getInputStream(); dis = new DataInputStream(is); os = s.getOutputStream(); dos = new DataOutputStream(os); serverReadSome(); //接受客户端发来的信息 }catch(IOException e){ e.printStackTrace(); } } public void actionPerformed(ActionEvent e){
//服务器点击按钮触发时间 try{ msg = ta1.getText(); dos.writeUTF(msg); ta2.append("小马:"+msg+"\n"); ta1.setText(""); ta1.requestFocus(); }catch(IOException ioe){ ioe.printStackTrace(); } } public void serverReadSome(){ try{ while(true){ msg = dis.readUTF(); ta2.append("小徐:"+msg+"\n"); } }catch(IOException ioe){ ioe.printStackTrace(); } } public static void main(String args[]){ new MySingleThreadServer1(); } }
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
我把GUI的初始化信息和事件驱动的信息放到了MySingleThreadServer1的构造函数中,使之new一个的时候就初始化该类。以上就是对Java Socket驱动的详细介绍。希望大家有所收获。
【编辑推荐】