Java Socket编程 案例

服务器端:
package test.socket;

//import java.net.*;
import java.io.*;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketTest_Server {
public static void main(String[] args) throws UnknownHostException,
IOException, ConnectException {
//服务器端端口号
ServerSocket aServerSocket = new ServerSocket(3434);
Socket aServer = null;
try {
aServer = aServerSocket.accept();
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(
aServer.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(
aServer.getOutputStream()));

String serverstring = null;
String clientstring = null;
System.out.println("hello! enter the bye to exit.");
System.out.print("Server:wait client");
serverstring = input.readLine();
boolean done = false;
while (!done) {
if (serverstring != null) {
out.println(serverstring);
out.flush();
}
clientstring = in.readLine();
if (clientstring != null)
System.out.println("client:" + clientstring);
System.out.print("server:");
serverstring = input.readLine();
if (serverstring.equals("bye"))
done = true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
aServer.close();
}

} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
aServerSocket.close();
}

}
}


客户端:

package test.socket;

import java.net.*;
import java.io.*;

public class SocketTest_SvrClit {
public static void main(String[] args) throws UnknownHostException,
IOException, ConnectException {
Socket aClient = null;
// IP和端口号
                     //IP可以是127.0.0.1或者localhost
aClient = new Socket("192.168.0.8", 3434); // InetAddress.getLocalHost()
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(
aClient.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(aClient
.getOutputStream()));

String clientString = null;
String serverString = null;
System.out.println("hello!enter bye to exit.");
boolean done = false;
while (!done) {
serverString = in.readLine();
if (serverString != null)
System.out.println("Server:" + serverString);
System.out.print("client:");
clientString = input.readLine();
if (clientString.equals("bye"))
done = true;
if (clientString != null) {
out.println(clientString);
out.flush();
}
}
in.close();
out.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
aClient.close();
}
}
}

你可能感兴趣的:(java,socket,IO,net,ServerSocket)