日期:2014-05-20 浏览次数:20793 次
package com.shengsiyuan.network.e3;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 监听端
*/
public class ServerTest1
{
private static ServerSocket serverSocket;
public static void main(String[] args) throws Exception
{
serverSocket = new ServerSocket(5000);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
byte[] buffer = new byte[200];
int length = 0;
String string = null;
while (-1 != (length = is.read(buffer, 0, buffer.length)))
{
string = new String(buffer, 0, length);
}
is.close();
socket.close();
serverSocket.close();
System.out.println(string);
}
}
package com.shengsiyuan.network.e3;
import java.io.OutputStream;
import java.net.Socket;
/**
* 发送字符串welcome
*/
public class ClientTest1
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("localhost", 5000);
OutputStream os=socket.getOutputStream();
os.write("welcome".getBytes());
os.close();
socket.close();
}
}
package com.shengsiyuan.network.e2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MainServer
{
private static ServerSocket serverSocket;
public static void main(String[] args) throws Exception
{
serverSocket = new ServerSocket(4000);
while (true)
{
Socket socket = serverSocket.accept();
// 启动读写线程
new ServerInputThread(socket).start();
new ServerOutputThread(socket).start();
}
}
}
class ServerInputThread extends Thread
{
private Socket socket;