服务端:

package NetWork;

import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Server implements ActionListener, Runnable {
JTextArea showArea;
JTextField msgText;
JFrame mainJframe;
JButton sentBtn;
JScrollPane JSPane;
JPanel pane;
Container con;
Thread thread = null;
ServerSocket serverSocket;
Socket connectToClient;
DataInputStream inFromClient;
DataOutputStream outToClient;

public Server() {
// 设置界面
mainJframe = new JFrame("TCP聊天服务端");
con = mainJframe.getContentPane();
showArea = new JTextArea();
showArea.setEditable(false);
showArea.setLineWrap(true);
JSPane = new JScrollPane(showArea);
msgText = new JTextField();
msgText.setColumns(30);
msgText.addActionListener(this);
sentBtn = new JButton("发送");
sentBtn.addActionListener(this);
pane = new JPanel();
pane.setLayout(new FlowLayout());
pane.add(msgText);
pane.add(sentBtn);
con.add(JSPane, BorderLayout.CENTER);
con.add(pane, BorderLayout.SOUTH);
mainJframe.setLocation(300, 200);
mainJframe.setSize(500, 350);
mainJframe.setVisible(true);
mainJframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
;
try {
// 创建服务套接字
serverSocket = new ServerSocket(5500);
showArea.append("正在等待对话请求...\n");
// 侦听客户端的连接
connectToClient = serverSocket.accept();
inFromClient = new DataInputStream(connectToClient.getInputStream());
outToClient = new DataOutputStream(connectToClient.getOutputStream());
// 启动线程在后台来接收对方的消息
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
} catch (IOException e) {
showArea.append("对不起,不能创建服务器\n");
msgText.setEditable(false);
sentBtn.setEnabled(false);
}
}

public static void main(String[] args) {
new Server();
}

@Override // 响应按钮事件,发送消息给对方
public void actionPerformed(ActionEvent e) {
String s = msgText.getText();
if (s.length() > 0) {
try {
outToClient.writeUTF(s);
outToClient.flush();
showArea.append("我 :" + msgText.getText() + "\n");
msgText.setText(null);
} catch (IOException el) {
showArea.append("你的消息:“" + msgText.getText() + "”未能发出去!\n");
}
}
}

@Override
// 本线程负责将客户机传来的信息显示在对话区域
public void run() {
try {
while (true) {
showArea.append("客户端:" + inFromClient.readUTF() + "\n");
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

客户端:

package NetWork;

import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Client implements ActionListener, Runnable {
JTextArea showArea;
JTextField msgText;
JFrame mainJframe;
JButton sentBtn;
JScrollPane JSPane;
JPanel pane;
Container con;
Thread thread = null;
Socket connectToServer;
DataInputStream inFromServer;
DataOutputStream outToServer;

public Client() {
mainJframe = new JFrame("TCP聊天客户端");
con = mainJframe.getContentPane();
showArea = new JTextArea();
showArea.setEditable(false);
showArea.setLineWrap(true);
JSPane = new JScrollPane(showArea);
msgText = new JTextField();
msgText.setColumns(30);
msgText.addActionListener(this);
sentBtn = new JButton("发送");
sentBtn.addActionListener(this);
pane = new JPanel();
pane.setLayout(new FlowLayout());
pane.add(msgText);
pane.add(sentBtn);
con.add(JSPane, BorderLayout.CENTER);
con.add(pane, BorderLayout.SOUTH);
mainJframe.setLocation(700, 200);
mainJframe.setSize(500, 350);
mainJframe.setVisible(true);
mainJframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建套接字连接到服务器
try {
connectToServer = new Socket("localhost", 5500); // 本地IP
inFromServer = new DataInputStream(connectToServer.getInputStream());
outToServer = new DataOutputStream(connectToServer.getOutputStream());
showArea.append("连接成功,请说话...\n");
// 创建线程在后台处理对方的消息
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
showArea.append("抱歉,未能连接到服务器!\n");
msgText.setEditable(false);
sentBtn.setEnabled(false);
}
}

public static void main(String[] args) {
new Client();
}

@Override //
public void actionPerformed(ActionEvent e) {
String s = msgText.getText();
if (s.length() > 0) {
try {
outToServer.writeUTF(s);
outToServer.flush();
showArea.append("我 : " + msgText.getText() + "\n");
msgText.setText(null);
} catch (IOException e1) {
showArea.append("你的消息:“" + msgText.getText() + "”未能发送出去!\n");
}
}
}

// 本线程负责将服务器传来的消息显示在对话区域
public void run() {
try {
while (true) {
showArea.append("服务端 :" + inFromServer.readUTF() + "\n");
Thread.sleep(1000);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

结果展示:

java实现TCP通信(带界面)的更多相关文章

  1. Java 之 TCP 通信程序

    一.概述 TCP 通信能实现两台计算机之间的数据交互,通信的两端,要严格区分为客户端(Client)与服务端(Server). 两端通信时步骤: 1.服务端程序,需要事先启动,等待客户端的连接: 2. ...

  2. java实现 TCP通信

    //服务端import com.hl.bluetooth.util.CRC16; import com.hl.bluetooth.util.FrameCheckFailedException; imp ...

  3. java 网络编程之TCP通信和简单的文件上传功能

    */ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...

  4. TCP通信实现对接硬件发送与接收十六进制数据 & int与byte的转换原理 & java中正负数的表示

    今天收到的一份需求任务是对接硬件,TCP通信,并给出通信端口与数据包格式,如下: 1.首先编写了一个简单的十六进制转byte[]数组与byte[]转换16进制字符串的两个方法,如下: /** * 将十 ...

  5. 【Java】同步阻塞式(BIO)TCP通信

    TCP BIO 背景 网络编程的基本模型是Clien/Server模型,也就是两个进程之间进行相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的地址发起连接 ...

  6. Java网络编程之TCP通信

    一.概述 Socket类是Java执行客户端TCP操作的基础类,这个类本身使用代码通过主机操作系统的本地TCP栈进行通信.Socket类的方法会建立和销毁连接,设置各种Socket选项. Server ...

  7. 结对随即四则运算(带界面Java版)

    //随机四则运算类 public class 随机四则运算 { public static void main(String[] args) { new 界面();//进入随机四则运算的首界面 } } ...

  8. 【Java TCP/IP Socket】深入剖析socket——TCP通信中由于底层队列填满而造成的死锁问题(含代码)

    基础准备 首先需要明白数据传输的底层实现机制,在http://blog.csdn.net/ns_code/article/details/15813809这篇博客中有详细的介绍,在上面的博客中,我们提 ...

  9. 【Java TCP/IP Socket】基于NIO的TCP通信(含代码)

    NIO主要原理及使用 NIO采取通道(Channel)和缓冲区(Buffer)来传输和保存数据,它是非阻塞式的I/O,即在等待连接.读写数据(这些都是在一线程以客户端的程序中会阻塞线程的操作)的时候, ...

随机推荐

  1. ipmi常用的命令行命令

    前言 记录一些常用的命令行操作 命令 查询机器的电源状态 ipmitool -I lanplus -U admin -P admin -H 172.16.21.215 power status 硬重启 ...

  2. ubuntu无法关机

    在/etc/default/halt 增加下面 INIT_HALT = POWEROFF 另一种方法: I have the same problem and found a solution whi ...

  3. Python_爬虫_urllib解析库

    简介:提取网页保存到txt文件中 + 解析txt文件内容,取出内容 from urllib import request import re.json url="http://www.163 ...

  4. 【进阶之路】Redis基础知识两篇就满足(二)

    导言 大家好,我是南橘,一名练习时常两年半的java练习生,这是我在博客园的第二篇文章,当然,都是要从别处搬运过来的,不过以后新的文章也会在博客园同步发布,希望大家能多多支持^_^ 这篇文章的出现,首 ...

  5. day02-业务服务监控

    提供大量第三方工具,可以开发企业级服务监控平台,本章涉及文件与目录差异对比.HTTP质量监控.邮件告警等内容一.文件内容差异比对1.示例1 d = difflib.Differ() diff = d. ...

  6. CTF-lottery[git文件泄露利用+PHP弱类型]

    知识点:PHP弱类型 .git文件泄露 玩攻防世界 遇到一个题lottery  进去看看  分析玩法 我们发现 进入登陆用户都是初始值 金钱是20  彩票号码必须输入7位 然后看你输入的彩票号码有多少 ...

  7. Vegas媒体生成器是什么,有什么作用

    在专业视频剪辑软件-Vegas的界面中,有一个媒体生成器的界面,此界面包含HitFilm Light Flares,Pro Type Titler,测试图案,纯色,棋盘格,色彩渐变,噪声纹理,致谢字幕 ...

  8. leetcode187. 重复的DNA序列

    所有 DNA 都由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:"ACGAATTCCG".在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助.编写一个函数 ...

  9. C语言项目(一):学生信息管理系统

    实现方式:链表 结构定义 1 typedef struct MyStu MyStudent; 2 typedef struct node Node; 3 typedef Node *pNode; 4 ...

  10. Unity使用transform.Rotate进行三维旋转角度出现偏差

    Unity使用transform.Rotate进行三维旋转角度出现偏差 情形 最开始遇到该问题的情况比较复杂,另写了一个例子.情形如下: 一个立方体上挂载脚本: transform.Rotate(25 ...