服务端
package wanfeng;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server2 extends Thread {
private ServerSocket ss=null;
private int clientcounter=0;
public Server2()
{
try {
ss=new ServerSocket(9999);
} catch (IOException e) {
System.out.println("绑定端口失败!"+e.getMessage());
}
}
public void run()
{
Socket s= null;
try {
while(true) {
s = ss.accept();
clientcounter++;
SockerThread sockerThread = new SockerThread(s, clientcounter);//没次接受一个,开启一个多线程
sockerThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(ss!=null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Server2 server2=new Server2();
server2.start();
}
}
服务端实现开启多线程
package wanfeng;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class SockerThread extends Thread {
private Socket s = null;
private int clientcounter=0;
public SockerThread(Socket s,int clientcounter)
{
this.s=s;
this.clientcounter=clientcounter;
System.out.println("有新线程连接了:当前线程数为:"+clientcounter+"线程id:"+currentThread().getId());
}
public void run()
{
//InputStream inputStream=null;
try {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(s.getInputStream()));
/*inputStream=s.getInputStream();
byte[] buf=new byte[1024];
int num=inputStream.read(buf);
String string = new String(buf,0,num);*/
String string = "";
while((string = bufferedReader.readLine())!=null) {
System.out.println(s.getInetAddress().toString() + ": " + string + " " + "客户端id: " + clientcounter);
}
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
package wanfeng;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client2 {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Socket socket = new Socket("127.0.0.1",9999);
//OutputStream outputStream=socket.getOutputStream();
PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String str="";
while((str=scanner.nextLine())!=null)
{
out.println(str);
out.flush();
if(str.equals("q"))
break;
}
socket.close();
}
}