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();
}
}
Java Socket基础[备忘]的更多相关文章
- Socket网络通讯开发总结之:Java 与 C进行Socket通讯 + [备忘] Java和C之间的通讯
Socket网络通讯开发总结之:Java 与 C进行Socket通讯 http://blog.sina.com.cn/s/blog_55934df80100i55l.html (2010-04-08 ...
- 0. Java虚拟机系列备忘预览图
打算把Java虚拟机这块单独弄一个主题出来,做做备忘,结构如图所示: 后面还有一部分待更新...
- UITextView -- 基础备忘
UITextView 这篇文章只涉及到基本的使用,日后会写一些关于结合TextKit的备忘 基本属性 let screenSize = UIScreen.mainScreen().bounds.siz ...
- 【Socket】Java Socket基础编程
Socket是Java网络编程的基础,了解还是有好处的, 这篇文章主要讲解Socket的基础编程.Socket用在哪呢,主要用在进程间,网络间通信.本篇比较长,特别做了个目录: 一.Socket通信基 ...
- Java Socket 基础例子
1.服务器端代码 package com.lanber.socket; import java.io.DataInputStream; import java.io.DataOutputStream; ...
- JAVA Socket基础(简单实现)
学习Socket需要了解的几个概念: Socket 指的是互联网连接中的各个终结点.互联网连接是怎么创建的,通过IP地址加端口号,进行互通. A电脑(192.168.3.125:80)>> ...
- scala基础备忘
声明一个变量 声明一个常量 显式指定类型 定义一个main函数 package org.admln.scala class HelloScala { } object HelloScala { def ...
- java socket 基础操作
服务端: public class Server { public static void main(String[] args) throws Exception { //1.创建一个服务器端Soc ...
- Java输入输出流备忘
重要博客: http://blog.csdn.net/hguisu/article/details/7418161 File dir = new File("\\root"); ...
随机推荐
- 【t045】细菌
Time Limit: 1 second Memory Limit: 128 MB [问题描述] 近期,农场出现了D (1<= D <=15)种细菌.John 要从他的 N (1<= ...
- 开源:通用的日志分析工具(LogViewer)
工具介绍 本工具最早是制作出来查看我的 FTL(Fast Trace Log) 二进制日志文件的, 后来因为去做Java后台,经常看 SpringBoot, Tomcat 等的日志, 就简单重构了一下 ...
- MapReduce自定义InputFormat,RecordReader
MapReduce默认的InputFormat是TextInputFormat,且key是偏移量,value是文本,自定义InputFormat需要实现FileInputFormat,并重写creat ...
- opencc 繁体简体互转 (C++)
繁体字通常采用BIG5编码,简体字通常采用GBK或者GB18030编码,这种情况下,直接使用iconv(linux下有对应的命令,也有对应的C API供编程调用)就行.对于默认采用utf-8 ...
- jscript的常用文件操作
作者:朱金灿 来源:http://blog.csdn.net/clever101 1.重命名文件 var fso = new ActiveXObject("Scripting.FileSys ...
- How to configure spring boot through annotations in order to have something similar to <jsp-config> in web.xml?
JSP file not rendering in Spring Boot web application You will need not one but two dependencies (ja ...
- 使用elasticsearch遇到的一些问题以及解决方法(不断更新)
7.org.elasticsearch.transport.RemoteTransportException: Failed to deserialize exception response fro ...
- WPF 控制程序只能启动一次
原文:WPF 控制程序只能启动一次 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/jsyhello/article/details/7411898 ...
- 数据中台解析Hive SQL过程
一.数据中台解析SQL的目的: 数据中台需要对外提供数据特征查询的能力,因此中台查找并解析各个平台的sql,找出哪些表中的字段经常被使用,以便沉淀为特征,而我们要做的是找出sql中的数据表及其字段.以 ...
- Linux下编译,要下载tar.xz,而不要下载zip,因为换行的编码不一样,对.h.cpp没有影响,但是对脚本有影响 good
原因是 在win下编辑的时候,换行结尾是\n\r , 而在linux下 是\n,所以才会有 多出来的\r但是这个我是直接下载的官网文件解压的,没有动过啊. 破案了. linux下编译要下 .tar.x ...