日期:2014-05-20 浏览次数:20826 次
Socket s=ss.accept(); Client c=new Client(s); new Thread(c).start();
------解决方案--------------------
把socket变量做为全局变量试试,这样收和发两个线程都能看到
------解决方案--------------------
使用TCP协议来进行服务器端与客户端的通信
服务器端:
package com.aikaibo.network;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(5000);
//等待客服端的连接
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
os.write("hello".getBytes());
InputStream is = socket.getInputStream();
byte[] buffer = new byte[200];
int length = is.read(buffer);
System.out.println(new String(buffer, 0, length));
// byte[] buffer = new byte[200];
//
// int length = 0;
//
// while(-1 != (length = is.read(buffer, 0, buffer.length)))
// {
// String str = new String(buffer, 0, length);
// System.out.println(str);
// }
os.close();
ss.close();
socket.close();
}
}
客户端:
package com.aikaibo.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class TcpClient
{
public static void main(String[] args) throws Exception, IOException
{
//与服务器端建立好连接
Socket socket = new Socket("192.168.1.6", 5000);
InputStream is = socket.getInputStream();
byte[] buffer = new byte[200];
int length = is.read(buffer);
System.out.println(new String(buffer, 0, length));
// int length = 0;
// while(-1 != (length = is.read(buffer, 0, buffer.length)))
// {
// String str = new String(buffer, 0, length);
//
// System.out.println(str);
// }
OutputStream os = socket.getOutputStream();
os.write("wo".getBytes());
is.close();
os.close();
socket.close();
}
}