package com.xzc.gersang.servers;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
- Socket通讯服务器端
- @author 米强<如转载请保留作者和出处>
- @blog http://hi.baidu.com/mq612/blog
-
@blog http://blog.csdn.net/mq612
*/
public class ServerMain
{
public ServerMain()
{
try
{
// 构造服务器ServerSocket对象,参数为服务器端开放的端口号
ServerSocket ss = new ServerSocket(20000);
System.out.println("服务器准备就绪!");
// 死循环可以使服务器持续处于接收客户端状态
while (true)
{
// 该方法使程序阻塞,等待客户端的链接,当监听到客户端的链接,创建一个Socket对象与客户端单独会话
Socket s = ss.accept();
// 为了不影响服务器监听其它客户端,这里开启了一个线程,由线程处理与这个客户端的会话
new ServerThread().rs(s);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}public static void main(String[] args) throws UnknownHostException, IOException
{
new ServerMain();
}
}
/**
-
服务器端与客户端会话的线程
*/
class ServerThread
{
private Socket s = null;public void rs(Socket s)
{
this.s = s;
try
{
// 从Socket中获取输入流和输出流,由于我们只做一个简单的字符串通讯,所以采用BufferedRead和PrintStream来封装输入、输出流
InputStream in = s.getInputStream();byte b[] = new byte[11]; // $这个时候读完了,流也就关闭了,程序就不会向下执行了 while (in.read(b) != -1) { for(byte t : b) { System.out.println(Byte.toString(t)); } } byte o[] = {4,1,1,1}; s.getOutputStream().write(o); s.getOutputStream().flush(); } catch (IOException e) { e.printStackTrace(); }
}
}
客户端代码
public static void main(String[] args) throws Exception
{
// dir();
int i = 0;
while (true)
{
if (i == 0)
{
Socket s = new Socket("127.0.0.1", 20000);
byte b[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
s.getOutputStream().write(b);
s.getOutputStream().flush();
i++;
}
Thread.currentThread().sleep(500);
}
}