第5个回答 2013-07-18
import java.net.*;
import java.io.*;
public class MyClient implements Runnable
{
Socket clientSocket;
boolean flag=true;
Thread ConnenThread;
BufferedReader cin;
DataOutputStream cout;
public static void main(String args[])
{
new MyClient().ClientStart();
}
public void ClientStart()
{
try
{
clientSocket=new Socket("localhost",8080);
System.out.println("已建立连接!");
while(flag)
{
InputStream is=clientSocket.getInputStream();
cin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
cout=new DataOutputStream(os);
ConnenThread=new Thread(this);
ConnenThread.start();
String aline;
while((aline=cin.readLine())!=null)
{
System.out.println(aline);
if(aline.equals("byte"))
{
flag=false;
ConnenThread.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); }
}
}
}
上面是客户端
下面服务器端
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class MyServer implements Runnable
{
ServerSocket server=null;
Socket clientSocket;
boolean flag=true;
Thread ConnenThread;
BufferedReader sin;
DataOutputStream sout;
public static void main(String args[])
{
MyServer MS=new MyServer();
MS.ServerStart();
}
public void ServerStart()
{
try
{
server=new ServerSocket(8080);
System.out.println("端口号:"+server.getLocalPort());
while(flag)
{
clientSocket=server.accept();
System.out.println("连接已经建立完毕");