SERVER端代码:
package socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketManager {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
SocketManager manager = new SocketManager();
manager.doListen();
}
public void doListen() {
ServerSocket server = null;
try {
server = new ServerSocket(9991);
while (true) {
Socket client = server.accept();
new Thread(new SSocket(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if (server != null) {
try {
server.close();
} catch (IOException e) {
}
}
}
}
//服务器进程
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
this.client = client;
}
public void run() {
// DataInputStream input;
DataOutputStream output;
try {
// input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
//
// String listMsg = input.readUTF();
output.writeUTF("Recive: \r\n Thx...");
System.out.println("weiheshan");
// listMsg = input.readUTF();
//output.writeUTF("Recive Second: " + listMsg + " \r\n Thx...");
//System.out.println("Recive Second: " + listMsg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
CILENT端代码:
package socket;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 9990);
// OutputStream netOut = socket.getOutputStream();
DataInputStream in = new DataInputStream(socket.getInputStream());
String res = in.readUTF();
System.out.println("dashan"+res);
//
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}