Commit a2d1ccaa authored by fangzhipeng's avatar fangzhipeng

Initial commit

parents
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.paul0523</groupId>
<artifactId>netty</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>netty</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.paul0523;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
package com.paul0523;
import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
public class TcpClient {
public static void main(String[] args) throws Exception{
new TcpClient().start();
}
public void start() throws Exception{
Socket socket = new Socket("127.0.0.1", 8080);
new MyThread(socket).start();
while (true) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();
OutputStream outputStream = socket.getOutputStream();
if ("bye".equals(line)) {
outputStream.write(line.getBytes("utf-8"));
break;
}
outputStream.write(line.getBytes("utf-8"));
}
}
class MyThread extends Thread {
private Socket socket;
public MyThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
super.run();
try {
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
int count = 0;
while ((count = inputStream.read(bytes)) != -1) {
System.out.println(new String(bytes, 0, count, Charset.forName("utf-8")));
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.paul0523;
import java.io.BufferedReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
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;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TcpServer {
private ServerSocketChannel serverSocketChannel;
private Selector selector;
private SelectionKey selectionKey;
private Map<SelectionKey, String> cache = new HashMap<>();
public static void main(String[] args) throws Exception{
new TcpServer().start();
}
public TcpServer() throws Exception {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
selector = Selector.open();
selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void start() throws Exception{
while (true) {
selector.select();
for (Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); iterator.hasNext(); ) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
handleAccept(key);
} else if (key.isReadable()) {
handleRead(key);
} else if (key.isWritable()) {
handleWrite(key);
} else if (key.isConnectable()) {
handleConnet(key);
}
iterator.remove();
}
}
}
private void handleConnet(SelectionKey key) throws Exception {
System.out.println("建立连接");
}
private void handleWrite(SelectionKey key) throws Exception {
System.out.println("向通道写数据。。。");
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
SocketChannel socketChannel = (SocketChannel) key.channel();
socketChannel.write(byteBuffer);
key.interestOps(SelectionKey.OP_READ);
}
private void handleRead(SelectionKey key) throws Exception {
SocketChannel socketChannel = (SocketChannel) key.channel();
System.out.println(cache.containsKey(key));
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
byteBuffer.clear();
int readbytes = socketChannel.read(byteBuffer);
byteBuffer.flip();
if (readbytes > 0) {
byte[] bytes = new byte[readbytes];
byteBuffer.get(bytes, 0, readbytes);
System.out.println(new String(bytes, 0, readbytes, Charset.forName("utf-8")));
} else if (readbytes == -1) {
socketChannel.close();
return;
}
byteBuffer.flip();
key.attach(byteBuffer);
forCast(byteBuffer);
key.interestOps(SelectionKey.OP_WRITE);
}
private void forCast(ByteBuffer byteBuffer) {
Set<SelectionKey> keys = selector.keys();
for (SelectionKey key : keys) {
if (key == selectionKey) {
continue;
}
ByteBuffer newByteBuffer = ByteBuffer.wrap(byteBuffer.array());
newByteBuffer.position(0);
newByteBuffer.limit(byteBuffer.limit());
key.attach(newByteBuffer);
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
}
}
private void handleAccept(SelectionKey key) throws Exception {
SocketChannel socketChannel = ((ServerSocketChannel)key.channel()).accept();
socketChannel.configureBlocking(false);
SelectionKey selectionKey = socketChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(1024));
cache.put(selectionKey, null);
}
}
package com.paul0523;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment