Socket应用中最常用的几个API:
Accept:
用于产生"阻塞",直到接受到一个连接,并且返回一个客户端的Socket对象实例。"阻塞"是一个术语,它使程序运行暂时"停留"在这个地方,直到一个会话产生,然后程序继续;通常"阻塞"是由循环产生的。
getInputStream
获得网络连接输入,同时返回一个InputStream对象实例,。
getOutputStream
连接的另一端将得到输入,同时返回一个OutputStream对象实例。
开发一个最简单的client-server模型,少说废话,直接上实例:
服务器端:
import java.net.*;
import java.io.*;
public class Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss = new ServerSocket(10000);
while (true)
{
socket = ss.accept(); //服务器端程序运行到这里会阻塞,直到指定端口上有连接申请,程序才会继续向下执行。
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}
ss.close();
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Server();
}
}
客户端:
import java.io.*;
import java.net.*;
public class Client
{
Socket socket;
BufferedReader in;
PrintWriter out;
public Client()
{
try
{
socket = new Socket("xxx.xxx.xxx.xxx", 10000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader line = new BufferedReader(new InputStreamReader(System.in)); //将键盘中输入的内容包装成BufferedReader对象。
out.println(line.readLine()); //输出到服务器端。
line.close();
out.close();
in.close();
socket.close();
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Client();
}
}
如何完成多个客户端同时连接服务器端呢?看下面的实例:
import java.io.*;
import java.net.*;
public class Server extends ServerSocket
{
private static final int SERVER_PORT = 10000;
public Server() throws IOException
{
super(SERVER_PORT);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket); //为每一个客户端创建一个线程来进行连接
}
}
catch (IOException e)
{}
finally
{
close();
}
}
//--- CreateServerThread
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312"));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome ---");
start();
}
public void run()
{
try
{
String line = in.readLine();
while (!line.equals("bye")) //如果客户端发送了"bye"字符串,则服务器端与该客户端的连接关闭。
{
String msg = createMessage(line);
out.println(msg);
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
}
catch (IOException e)
{}
}
private String createMessage(String line)
{
xxxxxxxxx;
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
}
服务器端如何广播消息:
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
public class Server extends ServerSocket
{
private static ArrayList User_List = new ArrayList();
private static ArrayList Threader = new ArrayList();
private static LinkedList Message_Array = new LinkedList();
private static int Thread_Counter = 0;
private static boolean isClear = true;
protected static final int SERVER_PORT = 10000;
protected FileOutputStream LOG_FILE = new FileOutputStream("d:/connect.log", true);
public Server() throws FileNotFoundException, IOException
{
super(SERVER_PORT);
new Broadcast();
//append connection log
Calendar now = Calendar.getInstance();
String str = "[" + now.getTime().toString() + "] Accepted a connection\015\012";
byte[] tmp = str.getBytes();
LOG_FILE.write(tmp);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
finally
{
close();
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
//--- Broadcast
class Broadcast extends Thread
{
public Broadcast()
{
start();
}
public void run()
{
while (true)
{
if (!isClear)
{
String tmp = (String)Message_Array.getFirst();
for (int i = 0; i < Threader.size(); i++)
{
CreateServerThread client = (CreateServerThread)Threader.get(i);
client.sendMessage(tmp);
}
Message_Array.removeFirst();
isClear = Message_Array.size() > 0 ? false : true;
}
}
}
}
//--- CreateServerThread
class CreateServerThread extends Thread
{
private Socket client;
private BufferedReader in;
private PrintWriter out;
private String Username;
public CreateServerThread(Socket s) throws IOException
{
client = s;
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
out.println("--- Welcome to this chatroom ---");
out.println("Input your nickname:");
start();
}
public void sendMessage(String msg)
{
out.println(msg);
}
public void run()
{
try
{
int flag = 0;
Thread_Counter++;
String line = in.readLine();
while (!line.equals("bye"))
{
if (line.equals("l"))
{
out.println(listOnlineUsers());
line = in.readLine();
continue;
}
if (flag++ == 0)
{
Username = line;
User_List.add(Username);
out.println(listOnlineUsers());
Threader.add(this);
pushMessage("[< " + Username + " come on in >]");
}
else
{
pushMessage("<" + Username + ">" + line);
}
line = in.readLine();
}
out.println("--- See you, bye! ---");
client.close();
}
catch (IOException e)
{}
finally
{
try
{
client.close();
}
catch (IOException e)
{}
Thread_Counter--;
Threader.remove(this);
User_List.remove(Username);
pushMessage("[< " + Username + " left>]");
}
}
private String listOnlineUsers()
{
String s ="-+- Online list -+-\015\012";
for (int i = 0; i < User_List.size(); i++)
{
s += "[" + User_List.get(i) + "]\015\012";
}
s += "-+---------------------+-";
return s;
}
private void pushMessage(String msg)
{
Message_Array.addLast(msg);
isClear = false;
}
}
}