第一步 充分理解Socket
所謂socket通常也稱作
以J
重要的Socket API
注意
開發原理
服務器
客戶端
import
import java
public class Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss = new ServerSocket(
while (true)
{
socket = ss
in = new BufferedReader(new InputStreamReader(socket
out = new PrintWriter(socket
String line = in
out
out
in
socket
}
ss
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Server();
}
}
這個程序建立了一個服務器
{建立客戶端}
import java
import
public class Client
{
Socket socket;
BufferedReader in;
PrintWriter out;
public Client()
{
try
{
socket = new Socket(
in = new BufferedReader(new InputStreamReader(socket
out = new PrintWriter(socket
BufferedReader line = new BufferedReader(new InputStreamReader(System
out
line
out
in
socket
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Client();
}
}
這個客戶端連接到地址為xxx
第二步 多個客戶同時連接
在實際的網絡環境裡
設計原理
主程序監聽一端口
{實現消息共享}
import java
import
public class Server extends ServerSocket
{
private static final int SERVER_PORT =
public Server() throws IOException
{
super(SERVER_PORT);
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
catch (IOException e)
{}
finally
{
close();
}
}
//
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
out = new PrintWriter(client
out
start();
}
public void run()
{
try
{
String line = in
while (!line
{
String msg = createMessage(line);
out
line = in
}
out
client
}
catch (IOException e)
{}
}
private String createMessage(String line)
{
xxxxxxxxx;
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
}
這個程序監聽
第三步 實現信息共享:在Socket上的實時交流
網絡的偉大之一也是信息共享
設計原理
服務器端接受客戶端的連接請求
{源碼}
import java
import
import java
import java
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 =
private static boolean isClear = true;
protected static final int SERVER_PORT =
protected FileOutputStream LOG_FILE = new FileOutputStream(
public Server() throws FileNotFoundException
{
super(SERVER_PORT);
new Broadcast();
//append connection log
Calendar now = Calendar
String str =
byte[] tmp = str
LOG_FILE
try
{
while (true)
{
Socket socket = accept();
new CreateServerThread(socket);
}
}
finally
{
close();
}
}
public static void main(String[] args) throws IOException
{
new Server();
}
//
class Broadcast extends Thread
{
public Broadcast()
{
start();
}
public void run()
{
while (true)
{
if (!isClear)
{
String tmp = (String)Message_Array
for (int i =
{
CreateServerThread client = (CreateServerThread)Threader.get(i); From:http://tw.wingwit.com/Article/program/Java/hx/201311/25633.html