关于socket线程通信的一些知识整理
一般我们需要要让两台机子进行通信,需要创建一个Server 类,一个Client类,还需要创建一个线程类
server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8888);
int num=0;
System.out.println("服务器即将启动, 等待客户端启动。。。。。。");
while (true) {
Socket s = ss.accept();
ServerThread t = new ServerThread(s);
// 启动线程
t.start();
num++;
InetAddress ad= InetAddress.getLocalHost();
System.out.println(ad+"当前访问网站人数:"+num);
}
}
接着 接着创建Client
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s=new Socket("localhost",8888);
// 获取字节输出流
// s.geto
OutputStream str= s.getOutputStream();
PrintWriter pw=new PrintWriter(str);
pw.write("user:admin:1112, password:12364");
pw.flush();
s.shutdownOutput();
InputStream st= s.getInputStream();
InputStreamReader read=new InputStreamReader(st);
BufferedReader buf=new BufferedReader(read);
String s1=buf.readLine();
System.out.println("我是客户端, 服务端返回相应数据:"+s1);
buf.close();
read.close();
st.close();
pw.close();
str.close();
}
最后创建一个线程类
public class ServerThread extends Thread{
public ServerThread(Socket sockrt) {
super();
this.sockrt = sockrt;
}
Socket sockrt;
public void run()
{
Server s=new Server();
InputStream str = null;
try {
str = sockrt.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStreamReader read = null;
try {
read = new InputStreamReader(str,"gbk");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buf=new BufferedReader(read);
String lin = null;
try {
lin = buf.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(lin!=null)
{
System.out.println(" 我是服务器:客户端说:"+lin);
try {
lin=buf.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
sockrt.shutdownInput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream stream = null;
try {
stream = sockrt.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw=new PrintWriter(stream);
pw.write("欢迎您");
pw.flush();
pw.close();
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
str.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sockrt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样既可实现多用户访问服务器