<----------------------服务器端------------------------------->
//实现多线程的网络连接
package cnsocket;
import javaio;
import javanet;
public class SocketServerTrue {
public SocketServerTrue()
{
try {
//服务器开启一个端口
Systemoutprintln("等待连接");
ServerSocket ss= new ServerSocket(8090);
//等待连接,返回socket类型的对象
Socket s=ssaccept();
Systemoutprintln("连接成功,等待客户端输入信息!");
//得到客户端的信息
InputStreamReader isr=new InputStreamReader(sgetInputStream());
BufferedReader br=new BufferedReader(isr);
//向客户端传递信息
PrintWriter pw=new PrintWriter(sgetOutputStream(),true);
//实现从控制台输入数据
InputStreamReader isrS=new InputStreamReader(Systemin);
BufferedReader brS=new BufferedReader(isrS);
while(true)
{
//得到客户端的信息
String info=brreadLine();
//判断是否结束
if(infoequals("bye"))
{
Systemoutprintln("对话结束!");
sclose();
break;
}
Systemoutprintln("对方说:"+info);
//给客户端传递信息
String infoC=brSreadLine();
pwprintln(infoC);
if(infoCequals("bye"))
{
Systemoutprintln("对话结束!");
sclose();
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
/
@param args
/
public static void main(String[] args) {
// TODO Auto-generated method stub
SocketServerTrue ssm=new SocketServerTrue();
}
}
<---------------------------客户端-------------------------->
//客户端的(多线程)
package cnsocket;
import javaio;
import javanet;
public class SocketClientTrue {
public SocketClientTrue()
{
//去连接服务器
try {
Socket s=new Socket("127001",8090);
Systemoutprintln("连接成功,给服务器说话!");
//向服务器传递的信息
PrintWriter pw=new PrintWriter(sgetOutputStream(),true);
//得到服务器信息
InputStreamReader isr=new InputStreamReader(sgetInputStream());
BufferedReader br=new BufferedReader(isr);
//从控制台输入信息
InputStreamReader isrC=new InputStreamReader(Systemin);
BufferedReader brC=new BufferedReader(isrC);
while(true)
{
//给服务器说话
String infoS=brCreadLine();
pwprintln(infoS);
if(infoSequals("bye"))
{
Systemoutprintln("对话结束!");
sclose();
break;
}
//得到服务器的信息
String info=brreadLine();
if(infoequals("bye"))
{
Systemoutprintln("对话结束!");
sclose();
break;
}
Systemoutprintln("对方说:"+info);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
eprintStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
}
/
@param args
/
public static void main(String[] args) {
// TODO Auto-generated method stub
SocketClientTrue scm=new SocketClientTrue();
}
}
;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)