上回书说道,java中通过socket链接的两台计算机可以通过两端的两个Socket对象来读取和发送来自流的信息所以对于客户端和服务端只需要封装一个相同的收发信息的窗口就好
代码如下
package testpackage; import java.net.Socket; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; public class Server extends Thread{ Socket client=null; TalkFrame tf=new TalkFrame(); String s; BufferedReader is =null;//input from client PrintWriter os=null; public Server(Socket client){ this.client=client; tf.setVisible(true); try { is = new BufferedReader(new InputStreamReader(client.getInputStream())); os=new PrintWriter(client.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block } tf.send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub String str=tf.talkbox.getText(); s=s+" ME:"+str; tf.showbox.setText(s); os.println(str); os.flush(); } }); } public void run() { String readline; try { readline = is.readLine(); while(!readline.equals("bye")) { s=s+" HE:"+readline; tf.showbox.setText(s); readline = is.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
界面如下:
package testpackage; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.*; public class TalkFrame extends JFrame { public JPanel mainPanel=new JPanel(); public JTextArea showbox=new JTextArea(); public JPanel bottom=new JPanel(); public JButton send=new JButton("send"); public JTextArea talkbox=new JTextArea(); public TalkFrame() { this.add(mainPanel); mainPanel.add(showbox); showbox.setAutoscrolls(true); showbox.setPreferredSize(new Dimension(500,500)); showbox.setEditable(false); mainPanel.add(bottom); bottom.add(talkbox); bottom.add(send); talkbox.setPreferredSize(new Dimension(300,20)); mainPanel.setPreferredSize(new Dimension(500,550)); FlowLayout fl=new FlowLayout(); fl.setAlignment(FlowLayout.LEADING); fl.setAlignOnBaseline(true); this.setLayout(fl); this.pack(); //this.setVisible(true); } public static void main(String a[]) { new TalkFrame().setVisible(true); } }
对于接受和链接socket的方法 上篇已经提到过,只要吧两个socket用这个类封装一下就行了:https://www.cnblogs.com/mayeye/p/9571740.html