比爾最近接到一個項目
在學習Socket編程之前
Socket 的基本概念
我想你現在和我剛開始的時候一樣
Socket編程實現原理
從連接的建立到連接的結束
注意
Java中的Socket類
Java中提供兩個類(在包中)——Socket和ServerSocket來分別實現客戶端和服務器端Socket
ServerSocket類的常用構造器和主要方法
ServerSocket(int port) 在指定的端口號上產生一服務器端socket
Socket accept()
偵聽socket
Socket類的常見構造器和主要方法
Socket(String host
InputStream getInputStream() 返回socket的輸入流
OutputStream getOuputStream() 返回socket的輸出流
一個客戶服務器實例
了解了上面的一些基本知識以後
(服務器端)
/**
* <p>Title:EchoServer
* <p>Description: EchoServer create a echo
* @author Mac
* @version
*/
import
import java
public class EchoServer
{
public static void main (String[] args) throws IOException
{
ServerSocket echoServer = null;
try
{
echoServer = new ServerSocket(
}
catch(IOException e)
{
System
System
}
Socket echoClient = null;
try
{
echoClient = echoServer
}
catch(IOException e)
{
System
System
}
PrintWriter out = new PrintWriter(echoClient
//gets the socket
//if you remove the argument true
BufferedReader in = new BufferedReader(
new InputStreamReader(echoClient
//gets the socket
String strFromClient;
while((strFromClient = in
{
out
}
in
out
echoClient
echoServer
}
}
(客戶端)
/**
*<p>Title:EchoClient
*<p>Description: EchoClient creates a socket thereby getting a connection to
echo
* @author Mac Wang
* @version
*/
import
import java
public class EchoClient
{
public static void main(String[] args)
{
try
{
Socket echoClient = new Socket("yourhostname"
//creat a new socket connected to host and port
PrintWriter out = new PrintWriter(echoClient
BufferedReader in = new BufferedReader(
new InputStreamReader(echoClient
String fromServer
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System
//gets the system input stream and opens a BufferedReader on it
while ((fromUser = stdIn
{
if (fromUser
//when user types "bye" then end
System
out
fromServer = in
System
}
out
in
echoClient
}
catch(UnknownHostException e)
{
System
System
}
catch(IOException e)
{
System
System
}
}
}
現在大家可以分別運行Server和Client
從問題
/**
*<p>Title:EchoMultiServer </p>
*<p>Description: EchoServer create a echo
multi
* @author Mac Wang
* @version
*/
import
import java
class EchoMultiServerThread extends Thread
{
private Socket echoClient = nul
From:http://tw.wingwit.com/Article/program/Java/hx/201311/27141.html