放两个例子,作为自己学习的纪念碑
TCP/Socket编程练习题: 1.客户端服务器通信
OneServer.java
import
import
import
import
import
import
public class OneServer {
public static void main(String args[]) {
ServerSocket server = null;
try{
server = new ServerSocket(12355);
System.out.println("服务器启动:" + server.getInetAddress() + ":" + server.getLocalPort());
while(true) {
Socket socket = server.accept();
System.out.println("客户端连接:" + socket.getInetAddress() + ":" + socket.getPort());
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
String line;
while((line = is.readLine()) != null) {
System.out.println("收到:" + line);
if(line.equals("bye")) {
break;
}
else {
os.println(sin.readLine());
os.flush();
}
}
is.close();
os.close();
socket.close();
}
}catch(IOException e) {
e.printStackTrace();
}finally {
try{
server.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
OneClient.java
import
import
import
import
import
public class OneClient {
public static void main(String args[]) {
try{
Socket socket = new Socket("localhost", 12355);
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
String readline;
while((readline = sin.readLine()) != null) {
os.println(readline);
os.flush();
String responseline = is.readLine();
System.out.println("收到回复:" + responseline);
}
is.close();
os.close();
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
2.使用多线程处理多个客户端
ManyServer.java
import
import
import
public class ManyServer {
public static void main(String args[]) {
ServerSocket server = null;
try{
server = new ServerSocket(12355);
System.out.println("服务器启动:" + server.getInetAddress() + ":" + server.getLocalPort());
while(true) {
Socket socket = server.accept();
System.out.println("客户端连接:" + socket.getInetAddress() + ":" + socket.getPort());
new ServerThread(socket).start();
}
} catch(IOException e) {
e.printStackTrace();
}finally {
try{
server.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
ServerThread.java
import
import
import
import
import
public class ServerThread extends Thread {
Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
try{
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
String line;
while((line = is.readLine()) != null) {
System.out.println("收到:" + line);
if(line.equals("bye")) {
break;
}
else {
os.println(sin.readLine());
os.flush();
}
}
is.close();
os.close();
socket.close();
}
catch(IOException e) {
e.printStackTrace();
}finally {
try{
socket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
Client端的程序就是OneClient.java
完毕了!
运行截图:
[attach]75563[/attach]
[attach]75564[/attach]
UDP通信:
UDPServer.java
import
import
import
import
public class UDPServer {
public static void main(String args[]) {
try {
DatagramSocket socket = new DatagramSocket(12355);
byte buf[] = new byte[1200];
DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
System.out.println("开始接收包");
while(true) {
socket.receive(receivePacket);
String name = receivePacket.getAddress().toString();
System.out.println("来自主机:" + name + "\n 端口:" + receivePacket.getPort());
String s = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("接受数据:"+s);
}
} catch(SocketException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
UDPClient.java
import
import
import
import
import
public class UDPClient {
public static void main(String args[]) {
try {
DatagramSocket socket = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost"); //InetAddress相当于一个IP的封装对象
String msg = "hello, I'm client!";
DatagramPacket sendPacket = new DatagramPacket(msg.getBytes(), msg.length(), host, 12355);
socket.send(sendPacket);
} catch(SocketException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
[attach]75566[/attach]
UDP组播,服务器发广播的例子:
UdpSessionServer.java
import *;
import *;
public class UdpSessionServer {
public static void main(String args[]) throws Exception {
MulticastSocket socket = new MulticastSocket(10001);
InetAddress group = InetAddress.getByName("239.255.8.0");
socket.joinGroup(group);
byte b[] = "你好,你现在收到的是我发给你的消息".getBytes();
DatagramPacket dgPacket = new DatagramPacket(b, b.length, group, 10001);
socket.send(dgPacket);
socket.close();
System.out.println("send message ok.");
}
}
UdpSessionClient.java
import *;
import *;
public class UdpSessionClient {
public static void main(String args[]) throws Exception {
MulticastSocket socket = new MulticastSocket(10001);
byte[] by = new byte[1024];
InetAddress group = InetAddress.getByName("239.255.8.0");
socket.joinGroup(group);
DatagramPacket dgPacket = new DatagramPacket(by, by.length, group, 10001); // 待接收的数据包。
socket.receive(dgPacket);
String str = new String(by);
System.out.println("接收到的内容:");
System.out.println(str);
socket.close();
}
}
运行结果:
下面是一个多人聊天对话的demo,技术:Socket通信+多线程
1.ServerThread.java
import
import
import
import
import
import java.util.Hashtable;
public class ServerThread extends Thread{
Socket socket;
BufferedReader is;
PrintWriter os;
Hashtable<String, ServerThread> clientlist;
String username;
public ServerThread(Socket socket,
Hashtable<String, ServerThread> clientlist) {
this.socket = socket;
this.clientlist = clientlist;
try {
System.out.println("try");
is = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
os = new PrintWriter(socket.getOutputStream());
this.username = is.readLine();
clientlist.put(username, this);
System.out.println(username + "链接:" + socket.getInetAddress() + ":"
+ socket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String line;
while ((line = is.readLine()) != null) {
System.out.println(username + "发给" + line);
if (line.equals("bye"))
break;
else {
String arr[] = line.split(":");
if (arr.length == 2) {
if (clientlist.containsKey(arr[0])) {
clientlist.get(arr[0]).send(username + ":" + arr[1]);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String message) {
System.out.println("发给:" + username + " " + message);
os.println(message);
os.flush();
}
}
2.ChatServer.java
import
import
import
import java.util.Hashtable;
public class ChatServer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server = null;
try {
server = new ServerSocket(12345);
System.out.println("服务器启动:"
+ server.getInetAddress().getLocalHost() + ":"
+ server.getLocalPort());
Hashtable<String, ServerThread> clientlist = new Hashtable<String, ServerThread>();
while (true) {
System.out.println("Server Accept");
Socket socket = server.accept();
new ServerThread(socket, clientlist).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.ClientThread.java
import
import
import
import
import
public class ClientThread extends Thread{
Socket socket;
BufferedReader is;
PrintWriter os;
public ClientThread(String username) {
try {
socket = new Socket("localhost", 12345);
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
os = new PrintWriter(socket.getOutputStream());
os.println(username);
os.flush();
} catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String readline;
while((readline = is.readLine()) != null) {
System.out.println(readline);
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void send(String message) {
os.println(message);
os.flush();
}
public void close() {
try {
is.close();
os.close();
socket.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
4.ChatClient.java
import
import
import
public class ChatClient {
public static void main(String args[]) throws Exception {
try {
ClientThread client = new ClientThread(args[0]);
client.start();
BufferedReader sin= new BufferedReader(new InputStreamReader(System.in));
String readline;
while((readline = sin.readLine()) != null) {
if(readline.equals("bye")) {
client.close();
System.exit(0);
}
client.send(readline);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
运行结果:
程序结构说明:
服务器端有一个线程队列Map记录客户端的连接,每每有一客户想给另一个客户发送消息,首先该客户发送信息到服务器端,发送内容包括接受者在Map中的Key(名字username)和发送的信息内容,服务器端收到信息以后,首先查询是否存在接受者,如果存在则调用接受者对应线程的send方法把刚才那位客户发来的消息转发给他
贴不上来,运行结果不要了。
[ 本帖最后由 lateraware 于 2014-4-16 11:56 编辑 ]