『壹』 在windows下用C語言如何實現socket網路編程,需要用到哪些頭文件或者庫
需要用到的頭文件包含:
#include <winsock2.h>
#include <windows.h>
與Linux環境下socket編程相比,windows環境多了一個步驟:啟動或者初始化winsock庫
Winsock,一種標准API,一種網路編程介面,用於兩個或多個應用程序(或進程)之間通過網路進行數據通信。具有兩個版本:
Winsock 1:
Windows CE平台支持。
頭文件:WinSock.h
庫:wsock32.lib
Winsock 2:
部分平台如Windows CE貌似不支持。通過前綴WSA可以區別於Winsock 1版本。個別函數如WSAStartup、WSACleanup、WSARecvEx、WSAGetLastError都屬於Winsock 1.1規范的函數;
頭文件:WinSock2.h
庫:ws2_32.lib
mswsock.h用於編程擴展,使用時必須鏈接mswsock.dll

(1)socket教程擴展閱讀
winsock庫的載入與卸載:
載入:int WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
載入成功,返回值為0。
WORD wVersionRequested:載入的winsock版本,使用宏MAKEWORD(x, y),x表示高位元組,y表示低位元組。然而使用時MAKEWORD(2, 2)。高位元組與低位元組相同~~
LPWSADATA lpWSAData:WSADATA結構的指針,傳入參數後,系統幫助我們填充版本信息。有興趣的可以看看結構體內容,不過基本用不著。
卸載:int WSACleanup(void);比起載入,卸載的函數真是輕松愉快。
『貳』 java Socket開發 關於報文傳遞和接收
看 Oracle 官方教程,同步式的 Socket 就是傳統的一問一答方式,它就是你需要的。
客戶端先 socket.getOutputStream().write(...); 之後到 socket.getInputStream().read(byte[]) 在循環中讀取直到 read 方法返回 -1 或你期望的位元組數已經全部收到了就停下來,如果不嘗試停下來,後面的 read 將會阻塞等待。
http://docs.oracle.com/javase/tutorial/networking/sockets/index.html
基於性能改進,一般我們需要使用 NIO 非同步的 socket,只需要一個線程負責通信,每個線程都有自己的出站消息隊列和入站消息隊列,以線程為 key 區分開,通信線程只負責把各自的消息從出站隊列中發送去並把收到的消息放入入站隊列中,應用程序線程就去各自的消息隊列中取消息就可以了。因為每個應用線程有各自的消息隊列,我們把消息放入出站隊列之後就到入站隊列上用同步鎖等待的方法阻塞到有消息回答時為止。
關於 NIO non-blocking 非阻塞式 socket,下面有一個 NBTimeServer 例子,它講的是服務端。客戶端與此類似,
http://docs.oracle.com/javase/7/docs/technotes/guides/io/example/index.html
NIO 通信線程樣例。
publicvoidrun()
{
inttip=0;
try
{
selector=Selector.open();
SelectionKeyk=channel.register(selector,getInterestOptions());
k.attach(thread);//把當前線程綁定到附件中。
this.running=true;
statusChanged(Status.CONNECTED);
while(this.isRunning())
{
//select()isablockingoperation.
inteventCount=selector.select();
debug("[MC.Debug]PollingTCPevents..."+eventCount);
if(eventCount>0&&channel.isOpen()&&this.isRunning())
{
Setkeys=selector.selectedKeys();
for(Iteratoriter=keys.iterator();iter.hasNext();iter.remove())
{
SelectionKeykey=(SelectionKey)iter.next();
Threadthread=(Thread)key.attachment();
if(!key.isValid())
{//channelisclosing.
break;
}
process(key);//處理讀取消息並把消息放入thread對應的隊列。//寫出消息類似的,不過在register時需要注冊寫出允許的事件,
}
}
}
}
『叄』 java編程中,Socket通信是怎麼實現的
java編程對於Socket之間的通信過程如下:
服務端往Socket的輸出流裡面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流裡面寫東西,然後服務端對應的Socket的輸入流就可以讀出對應的內容。下面來看一些服務端與客戶端通信的例子:
publicclassServer{
publicstaticvoidmain(Stringargs[])throwsIOException{
//為了簡單起見,所有的異常信息都往外拋
intport=8899;
//定義一個ServerSocket監聽在埠8899上
ServerSocketserver=newServerSocket(port);
//server嘗試接收其他Socket的連接請求,server的accept方法是阻塞式的
Socketsocket=server.accept();
//跟客戶端建立好連接之後,我們就可以獲取socket的InputStream,並從中讀取客戶端發過來的信息了。
Readerreader=newInputStreamReader(socket.getInputStream());
charchars[]=newchar[64];
intlen;
StringBuildersb=newStringBuilder();
while((len=reader.read(chars))!=-1){
sb.append(newString(chars,0,len));
}
System.out.println("fromclient:"+sb);
reader.close();
socket.close();
server.close();
}
}客戶端代碼
Java代碼publicclassClient{
publicstaticvoidmain(Stringargs[])throwsException{
//為了簡單起見,所有的異常都直接往外拋
Stringhost="127.0.0.1";//要連接的服務端IP地址
intport=8899;//要連接的服務端對應的監聽埠
//與服務端建立連接
Socketclient=newSocket(host,port);
//建立連接後就可以往服務端寫數據了
Writerwriter=newOutputStreamWriter(client.getOutputStream());
writer.write("HelloServer.");
writer.flush();//寫完後要記得flush
writer.close();
client.close();
}
}
『肆』 怎麼用java的socket進行文件傳輸誰能給個簡單的例子,包括發送端和接收端。
java中的網路信息傳輸方式是基於TCP協議或者UD協議P的,socket是基於TCP協議的
例子1
(1)客戶端程序:
import java.io.*;
import java.net.*;
public class Client
{  public static void main(String args[])
   {  String s=null;
      Socket mysocket;
      DataInputStream in=null;
      DataOutputStream out=null;
      try{
          mysocket=new Socket("localhost",4331);
          in=new DataInputStream(mysocket.getInputStream());
          out=new DataOutputStream(mysocket.getOutputStream()); 
          out.writeUTF("你好!");//通過 out向"線路"寫入信息。
          while(true)
            { 
               s=in.readUTF();//通過使用in讀取伺服器放入"線路"里的信息。堵塞狀態,
                             //除非讀取到信息。
               out.writeUTF(":"+Math.random());
               System.out.println("客戶收到:"+s);
               Thread.sleep(500);
            } 
         }
       catch(IOException e)
         {  System.out.println("無法連接");
         }
       catch(InterruptedException e){}
   } 
}
(2)伺服器端程序:
import java.io.*;import java.net.*;
public class Server
{ public static void main(String args[])
  {  ServerSocket server=null;
     Socket you=null;String s=null;
     DataOutputStream out=null;DataInputStream  in=null;
     try{ server=new ServerSocket(4331);}
      catch(IOException e1){System.out.println("ERRO:"+e1);} 
     try{  you=server.accept();
           in=new DataInputStream(you.getInputStream());
           out=new DataOutputStream(you.getOutputStream());
           while(true)
           {
             s=in.readUTF();// 通過使用in讀取客戶放入"線路"里的信息。堵塞狀態,
                             //除非讀取到信息。
             out.writeUTF("你好:我是伺服器");//通過 out向"線路"寫入信息.
             out.writeUTF("你說的數是:"+s);
             System.out.println("伺服器收到:"+s);
             Thread.sleep(500);
           }
        }
     catch(IOException e)
         {  System.out.println(""+e);
         }
       catch(InterruptedException e){}
   }
}
例子(2)
(1) 客戶端
import java.net.*;import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{  Button 計算;TextField 輸入三邊長度文本框,計算結果文本框;
   Socket socket=null;
   DataInputStream in=null; DataOutputStream out=null;
   Thread thread; 
   public void init()
   {  setLayout(new GridLayout(2,2));
      Panel p1=new Panel(),p2=new Panel(); 
      計算=new Button(" 計算");
      輸入三邊長度文本框=new TextField(12);計算結果文本框=new TextField(12);
      p1.add(new Label("輸入三角形三邊的長度,用逗號或空格分隔:"));
    p1.add( 輸入三邊長度文本框);
      p2.add(new Label("計算結果:"));p2.add(計算結果文本框);p2.add(計算);
      計算.addActionListener(this);
      add(p1);add(p2);
   }
   public void start()
   {  try
         {  //和小程序所駐留的伺服器建立套接字連接:
            socket = new Socket(this.getCodeBase().getHost(), 4331); 
            in =new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
         } 
      catch (IOException e){}
      if(thread == null)
        {  thread = new Thread(this);
           thread.start();
        }
   }
   public void run()
   {  String s=null;
      while(true)
       {    try{  s=in.readUTF();//堵塞狀態,除非讀取到信息。
                  計算結果文本框.setText(s);
               }
           catch(IOException e) 
{  計算結果文本框.setText("與伺服器已斷開");
   break;
}   
       }
  }
  public void actionPerformed(ActionEvent e)
  {  if(e.getSource()==計算)
      {  String s=輸入三邊長度文本框.getText();
         if(s!=null)
           {  try {  out.writeUTF(s);
                  }
              catch(IOException e1){} 
           }               
     }
  }
}
 (2) 伺服器端
import java.io.*;import java.net.*;
import java.util.*;import java.sql.*;
public class Computer_server 
{  public static void main(String args[])
   {  ServerSocket server=null;Server_thread thread;
      Socket you=null;
      while(true) 
       {  try{  server=new ServerSocket(4331);
             }
          catch(IOException e1) 
             {  System.out.println("正在監聽"); //ServerSocket對象不能重復創建。
             } 
          try{  you=server.accept();
                System.out.println("客戶的地址:"+you.getInetAddress());
             }
         catch (IOException e)
             {  System.out.println("正在等待客戶");
             }
         if(you!=null) 
             {  new Server_thread(you).start(); //為每個客戶啟動一個專門的線程。  
             }
         else 
             {  continue;
             }
      }
   }
}
class Server_thread extends Thread
{  Socket socket;Connection Con=null;Statement Stmt=null;
   DataOutputStream out=null;DataInputStream  in=null;int n=0;
   String s=null;
   Server_thread(Socket t)
   {  socket=t;
      try {  in=new DataInputStream(socket.getInputStream());
             out=new DataOutputStream(socket.getOutputStream());
          }
      catch (IOException e)
          {}
   }  
   public void run()        
   {  while(true)
      {  double a[]=new double[3] ;int i=0;
         try{  s=in.readUTF();堵塞狀態,除非讀取到信息。
    StringTokenizer fenxi=new StringTokenizer(s," ,");
                 while(fenxi.hasMoreTokens())
                   {  String temp=fenxi.nextToken();
                      try{  a[i]=Double.valueOf(temp).doubleValue();i++;
                         }
                      catch(NumberFormatException e)
  {  out.writeUTF("請輸入數字字元");
                         }
                   }
                double p=(a[0]+a[1]+a[2])/2.0;
                out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
                sleep(2);    
            }
         catch(InterruptedException e){}
         catch (IOException e) 
            {  System.out.println("客戶離開");
  break;
            }
      }
   } 
}
這些例子都是Java2實用教程上的.