package newtest;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset; public class TcpServer
{
//用于检测所有Channel状态的selector
private Selector selector = null;
//定义编码格式
private Charset charset = Charset.forName("UTF-8"); public void init()throws IOException
{
selector = Selector.open();
//通过open方法来打开一个未绑定的ServerSocketChannel实例
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 8899);
//将该ServerSocketChannel绑定到指定IP地址
server.socket().bind(isa);
//设置ServerSocket以非阻塞方式工作
server.configureBlocking(false);
//将Server注册到指定Selector对象
server.register(selector, SelectionKey.OP_ACCEPT); while(selector.select() > 0)
{
//依次处理Selector上的每个已选择的SelectionKey
for(SelectionKey sk : selector.selectedKeys())
{
//从selector上的已选择Key集中删除正在处理的SelectionKey
selector.selectedKeys().remove(sk);
//如果sk对应的通道包含客户端的连接请求
if(sk.isAcceptable())
{
//调用accept方法接受连接,产生服务器端对应的SocketChannel
SocketChannel sc = server.accept();
//设置非阻塞方式工作
sc.configureBlocking(false);
//将该SocketChnnel也注册到selector
sc.register(selector, SelectionKey.OP_READ);
//将sk对应的Channel设置成准备接受其它请求
sk.interestOps(SelectionKey.OP_ACCEPT);
}
//如果sk对应的通道有数据需要读取
if(sk.isReadable())
{
//获取该SelectionKey对应的Channel,该Channnel中有可读的数据
SocketChannel sc = (SocketChannel)sk.channel();
//定义准备执行读取数据的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
//开始读数据
try
{
while(sc.read(buff) > 0)
{
buff.flip();
content += charset.decode(buff);
}
//打印从该sk对应的Channel里读到的数据
System.out.println("消息:" + content);
//将sk对应的Channel设置成准备下一次读取
sk.interestOps(SelectionKey.OP_READ);
}
//如果捕捉到该sk对应的Channel出现了异常,即表明该Channel对应的Client出现了问题
//所以从Selector中取消sk的注册
catch(IOException ex)
{
//从Selector中删除指定的SelectionKey
sk.cancel();
if(sk.channel() != null)
{
sk.channel().close();
}
}
// throw new IOException();
//如果content的长度大于0,即聊天信息不为空
if(content.length() > 0)
{
//遍历该selector里注册的所有selectionKey
for(SelectionKey key : selector.keys())
{
//获取该channel是SocketChannel对象
Channel targetChannel = key.channel();
if(targetChannel instanceof SocketChannel)
{
//将读到的内容写入该Channel中
SocketChannel dest = (SocketChannel)targetChannel;
dest.write(charset.encode(content));
}
}
}
}
}
}
} public static void main(String[] args)throws IOException
{
System.out.println("===========TCP的server端启动=============");
new TcpServer().init();
}
}
package com.springboot.springbootswagger.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException; public class TcpClient {
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null; // constructor to put ip address and port
public TcpClient(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected"); // takes input from terminal
input = new DataInputStream(System.in); out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u.toString());
}
catch(IOException i)
{
System.out.println(i);
} // 待读入的String
String line = ""; // 一直读到Over字符停止
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
} // 关闭连接
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
} public static void main(String args[])
{
TcpClient client = new TcpClient("127.0.0.1", 8899);
}
}

TCP的socket连接的更多相关文章

  1. Http、tcp、Socket连接区别

    转自Http.tcp.Socket连接区别 相信不少初学手机联网开发的朋友都想知道Http与Socket连接究竟有什么区别,希望通过自己的浅显理解能对初学者有所帮助. 1.TCP连接 要想明白Sock ...

  2. java下tcp的socket连接案例

    package cn.stat.p4.ipdemo; import java.io.BufferedReader; import java.io.IOException; import java.io ...

  3. java下tcp的socket连接

    serverDemo package cn.stat.p4.ipdemo; import java.io.IOException; import java.io.InputStream; import ...

  4. 网络编程懒人入门(八):手把手教你写基于TCP的Socket长连接

    本文原作者:“水晶虾饺”,原文由“玉刚说”写作平台提供写作赞助,原文版权归“玉刚说”微信公众号所有,即时通讯网收录时有改动. 1.引言 好多小白初次接触即时通讯(比如:IM或者消息推送应用)时,总是不 ...

  5. windows redis 连接错误Creating Server TCP listening socket 127.0.0.1:637 9: bind: No error

    报错信息如下: [10036] 30 Dec 10:23:49.616 # Creating Server TCP listening socket 127.0.0.1:637 9: bind: No ...

  6. TCP连接、Http连接与Socket连接

    1.TCP连接 手机能够使用联网功能是因为手机底层实现了TCP/IP协议,可以使手机终端通过无线网络建立TCP连接.TCP协议可以对上层网络提供接口,使上层网络数据的传输建立在“无差别”的网络之上. ...

  7. 运用JAVA的concurrent.ExecutorService线程池实现socket的TCP和UDP连接

    运用JAVA的concurrent.ExecutorService线程池实现socket的TCP和UDP连接 最近在项目中可能要用到socket相关的东西来发送消息,所以初步研究了下socket的TC ...

  8. tomcat通过socket连接MySQL,不再占用服务端口【linux】

    MySQL连接方式的说明 http://icbm.iteye.com/blog/1840673 MySQL除了最常见的TCP连接方式外,还提供SOCKET(LINUX默认连接方式).PIPE和SHAR ...

  9. 比较 http连接 vs socket连接

    http连接 :短连接,客户端,服务器三次握手建立连接,服务器响应返回信息,连接关闭,一次性的socket连接:长连接,客户端,服务器三次握手建立连接不中断(通过ip地址端口号定位进程)及时通讯,客户 ...

随机推荐

  1. 五、SSD原理(Single Shot MultiBox Detector)

    主流的算法主要分为两个类型: (1)tow-stage R-CNN系列算法,其主要思路是先通过启发式方法(selective search)或者CNN网络(RPN)产生一些列稀疏的候选框,然后对这些候 ...

  2. Echarts案例-折线图

    一:先在官网下载 https://www.echartsjs.com/zh/download.html 然后再建立工程,导入这两个包: 写代码: <!DOCTYPE html> <h ...

  3. 安装APK时报错:Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]

    安装APK时报错:Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI] 可以使用adb install -t 解决 对于已经在手机的文件可以使用pm ...

  4. sql注入笔记-sqlite

    1. SQLite 1. 常用语句及基本结构 (1)sqlite因为其比较简易每个db文件就是一个数据库,所以不存在information_schema数据库,但存在类似作用的表sqlite_mast ...

  5. Jenkins与gitlib实现自动化部署与持续构建

    Jenkins概念 Jenkins是一个功能强大的应用程序,允许持续集成和持续交付项目,无论用的是什么平台.这是一个免费的源代码,可以处理任何类型的构建或持续集成.集成Jenkins可以用于一些测试和 ...

  6. arcgis python 删除一个数据库所有数据

    # -*- coding: cp936 -*- import xlrd # must init xlrd import arcpy import os def main(): arcpy.env.wo ...

  7. Flume-自定义 Interceptor(拦截器)

    使用 Flume 采集服务器本地日志,需要按照日志类型的不同,将不同种类的日志发往不同的分析系统. 在实际的开发中,一台服务器产生的日志类型可能有很多种,不同类型的日志可能需要发送到不同的分析系统. ...

  8. benchmark在postgresql上的安装及使用

     BenchmarkSQL是一款经典的开源数据库测试工具,内嵌了TPCC测试脚本,可以对EnterpriseDB.PostgreSQL.MySQL.Oracle以及SQL Server等数据库直接进行 ...

  9. insmod内核模块时提示Failed to find the folder holding the modules怎么办?

    答:笔者通过重新编译内核和根文件系统解决了此问题 (笔者使用的是openwrt系统) 分析: 1. ’Failed to find the folder holding the modules‘这句l ...

  10. [Java读书笔记] Effective Java(Third Edition) 第 4 章 类和接口

    第 15 条: 使类和成员的可访问性最小化 软件设计基本原则:信息隐藏和封装. 信息隐藏可以有效解耦,使组件可以独立地开发.测试.优化.使用和修改.   经验法则:尽可能地使每个类或者成员不被外界访问 ...