共有两个文件,服务器端Server 和客户端Client
//Server1代码如下:
import java.net.*;
import java.io.*;
public class Server1 implements Runnable
{
ServerSocket server=null;
Socket clientSocket;
boolean flag=true; //是否结束的标记
Thread c; //向客户端发送信息的线程
BufferedReader sin;
DataOutputStream sout;
public static void main(String args[])
{
new Server1().ServerStart();
}
public void ServerStart()
{
try
{
server=new ServerSocket(5678);
System.out.println("端口号:"+server.getLocalPort());
while(flag)
{
clientSocket=server.accept();
System.out.println("已经建立连接。");
InputStream is=clientSocket.getInputStream();
sin= new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
sout=new DataOutputStream(os); //获得本地输出流
c=new Thread(this);
c.start(); //启动线程,向客户端发送信息
String aline;
while((aline=sin.readLine())!=null) //接受客户端的信息
{
System.out.println(aline);
if(aline.equals("bye"))
{
flag=false;
c.interrupt();
break;
}
}
sout.close();
os.close();
sin.close();
is.close();
clientSocket.close();
System.exit(0);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void run()
{
while(true)
{
try
{
int ch;
while((ch=System.in.read())!=-1)
{
sout.write((byte)ch);
if(ch=='/n')
{
sout.flush();
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void finalize() //析构方法
{
try
{
server.close();
}
catch(IOException e)
{
System.out.print(e);
}
}
}
//Client1代码如下
import java.net.*;
import java.io.*;
public class Client1 implements Runnable
{
Socket clientSocket;
boolean flag=true;
Thread c;
BufferedReader cin;
DataOutputStream cout;
public static void main(String args[])
{
new Client1().ClientStart();
}
public void ClientStart()
{
try
{
clientSocket=new Socket("192.168.0.1",5678); //主机Server1的IP地址
System.out.println("已经建立连接");
while(flag)
{
InputStream is=clientSocket.getInputStream();
cin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
cout=new DataOutputStream(os);
c=new Thread(this);
c.start();
String aline;
while((aline=cin.readLine())!=null)
{
System.out.println(aline);
if(aline.equals("bye"))
{
flag=false;
c.interrupt();
break;
}
}
cout.close();
os.close();
cin.close();
is.close();
clientSocket.close();
System.exit(0);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public void run()
{
while(true)
{
try
{
int ch;
while((ch=System.in.read())!=-1)
{
cout.write((byte)ch);
if(ch=='/n')
{
cout.flush();
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}