这个插件包装了关于java Socket的一些比较常用的方法 使Socket用起来比较方便
package sockettest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.shouchan.socket.impl.Socket;
/**
*
* @author SHOUCHAN
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("对客户端文字发送:");
//接受文字的服务器
new Thread(new Runnable() {
public void run() {
Socket socket = new Socket(9000);
int i = 0;
while(i < 4){
Socket sk = socket.bindSocket();
server(sk);
i++;
}
}
}).start();
//发送文字的客户端(4个客户端)
Socket socket1 = null;
Socket socket2 = null;
Socket socket3 = null;
Socket socket4 = null;
try {
socket1 = new Socket(InetAddress.getLocalHost(), 9000);
socket1.sendValue("Hello World");
System.out.println("socket1: " + socket1.getValue());
socket2 = new Socket(InetAddress.getLocalHost(), 9000);
socket2.sendValue("Hello World");
System.out.println("socket2: " + socket2.getValue());
socket3 = new Socket(InetAddress.getLocalHost(), 9000);
socket3.sendValue("Hello World");
System.out.println("socket3: " + socket3.getValue());
socket1.sendValue("bye");
System.out.println("socket1: " + socket1.getValue());
socket4 = new Socket(InetAddress.getLocalHost(), 9000);
socket4.sendValue("Hello World");
System.out.println("socket4: " + socket4.getValue());
socket2.sendValue("bye");
System.out.println("socket2: " + socket2.getValue());
socket4.sendValue("bye");
System.out.println("socket4: " + socket4.getValue());
socket3.sendValue("bye");
System.out.println("socket3: " + socket3.getValue());
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
socket1.close();
socket2.close();
socket3.close();
socket4.close();
}
System.out.println("\n发送二进制文件");
//发送二进制文件
test1();
System.out.println("\n直接发送文件");
//直接发送文件
test2();
}
public static void server(final Socket socket) {
new Thread(new Runnable() {
public void run() {
while (true) {
String value = socket.getValue();
String host = socket.getSocket().getInetAddress().getHostName();
int port = socket.getSocket().getPort();
System.out.println(host + ":" + port + " - SAY: " + value);
socket.sendValue("server-_ .........");
if (value.equals("bye")) {
socket.close();
break;
}
}
}
}).start();
}