日期:2014-05-18 浏览次数:20833 次
package cn.dzr.tcp.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class RecieveMessage implements Runnable
{
Socket socket;
public RecieveMessage(Socket socket)
{
this.socket = socket;
}
public void run()
{
recvice();
}
private void recvice()
{
try
{
while(true)
{
InputStream in = socket.getInputStream();
byte[] buff = new byte[1024];
int len = in.read(buff);
String ip = socket.getLocalAddress().getHostAddress();
int port = socket.getPort();
int port2 = socket.getLocalPort();
String text = new String(buff,0,len);
System.out.println("收到 ip: "+ip +"; port:"
+port +"; loclport: "+port2+ "...content:"
+ text);
if( text.equals("886"))
{
System.out.println("他说再见,我也不再理他了!");
break;
}
}
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
package cn.dzr.tcp.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class SendMessage implements Runnable
{
Socket socket;
public SendMessage(Socket socket)
{
this.socket = socket;
}
public void run()
{
sendMessage();
}
private void sendMessage()
{
try
{
OutputStream out = socket.getOutputStream();
BufferedReader bufr = new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
String str = bufr.readLine();
out.write(str.getBytes());
if(str.equals("886"))
{
break;
}
}
try
{
Thread.sleep(20);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.close();
} catch (IOException e)
{
// TODO Auto-generated catch block