62,567
社区成员




//服务器开始代码(可以写到服务器main函数里作为测试使用)
ServerSocket server = new ServerSocket(9000);
while(true){
Socket client = server.accept();
SSocket ss = new SSocket(client);
new Thread(ss).start();
}
//服务器 接受/发送 类
class SSocket implements Runnable{
protected Socket client;
public Socket (Socket client){
this.client = client;
}
public void run() {
DataInputStream input = null;
DataOutputStream output = null;
try{
System.out.println("Thread:strat()");
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
String inputs = input.readUTF();
String value = inputs + "123";
output.writeUTF(value);
output.flush();
}catch(IOException e){
e.printStackTrace();
}
}
}
public class CSocket {
private String host;
private int port;
private Socket socket;
public CSocket(String host, int port) {
this.host = host;
this.port = port;
}
public boolean connect() {
boolean success = false;
try {
if(socket == null)
socket = new Socket(host, port);
success = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
public void send(String data) {
DataOutputStream output = null;
DataInputStream input = null;
try {
output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(data);
output.flush();
input = new DataInputStream(socket.getInputStream());
String result = input.readUTF();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendTest(){
CSocket csocket = new CSocket("127.0.0.1", 9000);
csocket.connect();
csocket.send("abcdefg");
System.out.println("------");
csocket.connect();
csocket.send("123456789");
}
public void sendTest(){
CSocket csocket = new CSocket("127.0.0.1", 9000);
csocket.connect();
csocket.send("abcdefg");
System.out.println("------");
CSocket cs = new CSocket("127.0.0.1", 9000);
cs.connect();
cs.send("123456789");
}