TCP网络程序
Posted dulute
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP网络程序相关的知识,希望对你有一定的参考价值。
服务器端
package text; import java.io.*; import java.net.*; public class MyTcp { private BufferedReader reader; private ServerSocket server; private Socket socket; void getserver(){ try { server = new ServerSocket(8998); System.out.println("服务器套接字已经创建成功"); while (true) { System.out.println("等待客户机的链接"); socket = server.accept(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); getClientMessage(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } private void getClientMessage() { // TODO Auto-generated method stub try { while ( true) { System.out.println("客户机"+ reader.readLine()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } try { if(reader == null){ reader.close(); } if(socket!= null){ socket.close(); } } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub MyTcp tcp = new MyTcp(); tcp.getserver(); } }
客户端
package text; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; public class MyClien extends JFrame{ private PrintWriter writer ; Socket socket ; private JTextArea ta = new JTextArea(); private JTextField tf = new JTextField(); Container cc; public MyClien(String title) { // TODO Auto-generated constructor stub super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cc = this.getContentPane(); final JScrollPane scrollPane = new JScrollPane(); scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED)); getContentPane().add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(ta); cc.add(tf, "South"); tf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub writer.println(tf.getText()); ta.append(tf.getText() + ‘ ‘); ta.setSelectionEnd(ta.getText().length()); tf.setText(""); } }); } private void connect() { ta.append("尝试连接 "); try { socket = new Socket("127.0.0.1", 8998); writer = new PrintWriter(socket.getOutputStream(),true); ta.append("完成链接 "); } catch (Exception e) { // TODO: handle exceptio e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub MyClien clien = new MyClien("向服务器发送数据"); clien.setSize(200,200); clien.setVisible(true); clien.connect(); } }
以上是关于TCP网络程序的主要内容,如果未能解决你的问题,请参考以下文章
20155201 李卓雯 《网络对抗技术》实验一 逆向及Bof基础