服务器端:
package com.dvte.boss.utils;
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
while (true) {
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
}
}
}
这个服务器端可以实现多个client的访问,但是同步的,当一个client取得跟服务器的连接以后,其它的client就只能等待。要解决这个问题可以用线程的方式实现
客户端:
package com.dvte.boss.utils;
import java.net.*;
import java.io.*;
public class Client {
static Socket server;
public static void main(String[] args) throws Exception {
server = new Socket(InetAddress.getLocalHost(), 5678);
BufferedReader in = new BufferedReader(new InputStreamReader(server
.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = wt.readLine();
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
System.out.println(in.readLine());
}
server.close();
}
}
以下是多线程的方式实现服务端:
package com.dvte.boss.utils;
import java.net.*;
import java.io.*;
public class ThreadServer extends Thread {
private Socket client;
public ThreadServer(Socket c) {
this.client = c;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
}
catch (IOException ex) {
}
finally {
}
}
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
while (true) {
ThreadServer mu = new ThreadServer(server.accept());
mu.start();
}
}
}