java socket
class="java" name="code">import java.io.*; import java.net.*; public class Server { public static void main(String[] args) throws IOException { // 创建server socket ServerSocket server = new ServerSocket(5678); while (true) { // 服务器接收到客户端的数据后,创建与此客户端对话的Socket Socket client = server.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while (true) { String str = in.readLine(); System.out.println(str); out.println("has receive:" + str); out.flush(); if (str.equals("end")) break; } client.close();// 不需要继续使用此连接时,关闭连接 } } }
import java.net.*; import java.io.*; public class Client { static Socket server; public static void main(String[] args) throws Exception { server = new Socket(InetAddress.getLocalHost(), 5678); BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while (true){ String str = wt.readLine(); out.println(str); out.flush(); if (str.equals("end")){ break; } System.out.println(in.readLine()); } server.close(); } }?
delphi socket
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ScktComp; type TForm1 = class(TForm) edt_send: TEdit; btn_send: TButton; btn_connect: TButton; edt_host: TEdit; edt_port: TEdit; edt_receive: TEdit; lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; procedure btn_sendClick(Sender: TObject); procedure btn_connectClick(Sender: TObject); procedure ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket); private public end; var Form1: TForm1; ClientSocket: TClientSocket; implementation {$R *.dfm} procedure TForm1.btn_sendClick(Sender: TObject); begin ClientSocket.Socket.SendText(edt_send.Text+#13); end; procedure TForm1.btn_connectClick(Sender: TObject); begin ClientSocket.Close; ClientSocket.Host := edt_host.Text; ClientSocket.Port := StrToInt(edt_port.Text); ClientSocket.Open; // 指定处理事件 ClientSocket.OnRead := ClientSocketRead; end; procedure TForm1.ClientSocketRead(Sender: TObject; Socket: TCustomWinSocket); begin edt_receive.Text := Socket.ReceiveText; end; //****************************************************************************** //****************************************初始化,清理************************** //****************************************************************************** initialization ClientSocket := TClientSocket.Create(nil); // ClientSocket.ClientType := ctNonBlocking; finalization ClientSocket.Free; end.?