import java.net.*;
import java.io.*;
public class SocketServiceTest
{
public static void main(String[] args) throws Exception
{
ServerSocket serverSocket = new ServerSocket(10002);
Socket socket = null;
try
{
while (true)
{
socket = serverSocket.accept();
System.out.println("socket连接:" + socket.getRemoteSocketAddress().toString());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true)
{
String readLine = in.readLine();
System.out.println("收到消息" + readLine);
if("end".equals(readLine))
break;
}
}
}
catch (SocketException se)
{
System.out.println("客户端断开连接");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
System.out.println("socket关闭:" + socket.getRemoteSocketAddress().toString());
socket.close();
}
}
}(为什么jfsdkof 没有显示出来? 自己想)
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class MultithreadJIoSocketTest
{
public static void main (String[] args) throws Exception
{
ServerSocket serverSocket = new ServerSocket(10002);
Thread thread = new Thread(new Accptor(serverSocket));
thread.start();
}
}
import java.io.*;
import java.net.*;
public class Accptor implements Runnable
{
private ServerSocket serverSocket;
public Accptor(ServerSocket serverSocket)
{
this.serverSocket = serverSocket;
}
public void run()
{
while (true)
{
Socket socket = null;
try
{
socket = serverSocket.accept();
if(socket != null)
{
System.out.println("收到了socket:" + socket.getRemoteSocketAddress().toString());
Thread thread = new Thread(new Processor(socket));
thread.start();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
import java.io.*;
import java.net.*;
public class Processor implements Runnable
{
private Socket socket;
public Processor(Socket socket)
{
this.socket = socket;
}
public void run()
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readLine;
while(true)
{
readLine = in.readLine();
System.out.println("收到消息" + readLine);
if("end".equals(readLine))
{
break;
}
//客户端断开连接
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (SocketException se)
{
System.out.println("客户端断开连接");
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
try
{
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
package io;
//: io/GetChannel.java
// Getting channels from streams
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
// Write a file:
FileChannel fc =
new FileOutputStream("data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
// Add to the end of the file:
fc =
new RandomAccessFile("data.txt", "rw").getChannel();
fc.position(fc.size()); // Move to the end
fc.write(ByteBuffer.wrap("Some more".getBytes()));
fc.close();
// Read the file:
fc = new FileInputStream("data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while(buff.hasRemaining())
System.out.print((char)buff.get());
}
}
/* Output:
Some text Some more
*///:~package io;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.concurrent.*;
import java.io.*;
public class FileLocking {
public static void main(String[] args) throws Exception {
FileOutputStream fos= new FileOutputStream("file.txt");
FileLock fl = fos.getChannel().tryLock();
if(fl != null) {
System.out.println("Locked File");
FileChannel fc =fos.getChannel();
fc.write(ByteBuffer.wrap("Some textssss".getBytes()));
TimeUnit.MILLISECONDS.sleep(1000);
fl.release();
System.out.println("Released Lock");
}
fos.close();
}
} /* Output:
Locked File
Released Lock
*///:~
package io;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
/**
* 测试NIO中的文件锁:三个线程争抢文件锁,获得锁后向文件中写数据,然后再释放文件锁。
*
* @author aofeng <a href="mailto:aofengblog@163.com>aofengblog@163.com</a>
*/
public class LockTest implements Runnable {
public void run() {
Thread curr = Thread.currentThread();
System.out.println("Current executing thread is " + curr.getName());
URL url = LockTest.class.getClassLoader().getResource("file.txt");
//路径问题
//http://www.cnblogs.com/rongxh7/archive/2010/04/22/1718178.html
//
RandomAccessFile raf = null;
FileChannel fc = null;
FileLock lock = null;
try {
//就是这里的路径问题, 为什么要替换%20 去上面的资料里看
raf = new RandomAccessFile(url.getPath().replaceAll("%20"," "), "rw");
fc = raf.getChannel();
System.out.println(curr.getName() + " ready");
// 轮流获得文件独占锁。
while (true) {
try {
lock = fc.lock();
break;
} catch (OverlappingFileLockException e) {
Thread.sleep(1 * 1000);
}
}
if (null != lock) {
System.out.println(curr.getName() + " get filelock success");
fc.position(fc.size());
fc.write(ByteBuffer.wrap((curr.getName() + " write data. ")
.getBytes()));
} else {
System.out.println(curr.getName() + " get filelock fail");
}
fc.close();
raf.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 注意:要先释放锁,再关闭通道。
if (null != lock && lock.isValid()) {
try {
lock.release();
System.out.println(curr.getName() + " release filelock");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new LockTest());
t1.setName("t1");
Thread t2 = new Thread(new LockTest());
t2.setName("t2");
Thread t3 = new Thread(new LockTest());
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}ok现在我们看看在网络中,nio是在怎么运作的
public static void acceptConnections( int port) throws Exception {
// 打开一个 Selector
Selector acceptSelector = SelectorProvider.provider().openSelector();
// 创建一个 ServerSocketChannel ,这是一个 SelectableChannel 的子类
ServerSocketChannel ssc = ServerSocketChannel.open();
// 将其设为 non-blocking 状态,这样才能进行非阻塞 IO 操作
ssc.configureBlocking( false );
// 给 ServerSocketChannel 对应的 socket 绑定 IP 和端口
InetAddress lh = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(lh, port);
ssc.socket().bind(isa);
// 将 ServerSocketChannel 注册到 Selector 上,返回对应的 SelectionKey
ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
int keysAdded = 0;
// 用 select() 函数来监控注册在 Selector 上的 SelectableChannel
// 返回值代表了有多少 channel 可以进行 IO 操作 (ready for IO)
while ((keysAdded = acceptSelector.select()) > 0) {
// selectedKeys() 返回一个 SelectionKey 的集合,
// 其中每个 SelectionKey 代表了一个可以进行 IO 操作的 channel 。
// 一个 ServerSocketChannel 可以进行 IO 操作意味着有新的 TCP 连接连入了
Set<SelectionKey> readyKeys = acceptSelector.selectedKeys();
Iterator<SelectionKey> i = readyKeys.iterator();
while (i.hasNext()) {
SelectionKey sk = (SelectionKey) i.next();
// 需要将处理过的 key 从 selectedKeys 这个集合中删除
i.remove();
// 从 SelectionKey 得到对应的 channel
ServerSocketChannel nextReady =(ServerSocketChannel) sk.channel();
// 接受新的 TCP 连接
Socket s = nextReady.accept().socket();
// 把当前的时间写到这个新的 TCP 连接中
PrintWriter out =new PrintWriter(s.getOutputStream(), true );
Date now = new Date();
out.println(now);
// 关闭连接
out.close();
}
}
}
原文:http://blog.csdn.net/dlf123321/article/details/40047079